在上传图像时,如果我使用req.file.buffer
中的数据多数民众赞成在{.1}}这是一个数字数组..缓冲区。它将图像正确上传到AWS s3。
但是我需要在...之前调整图像大小,所以我试图使用jimp,就像这样:
const photo = await jimp.read(req.file.buffer)
await photo.cover(300, 300);
然后将其传递给aws设置:
const s3 = new AWS.S3()
const params = {
Bucket: 'jamsession-images',
Key: req.body.photo,
// here in body is a buffer just like the one in req.file.buffer
Body: photo.bitmap.data
};
s3.upload(params, function (err, data) {
if (err) {
console.log(err);
}
console.log('****************** success');
});
但是,如果我这样做了..它会将图像上传到aws s3 ..但图像已损坏
我在这里做什么?我认为aws s3需要在budy缓冲区中...而且我认为在jimp完成缩放图像之后..该新缓冲区可以工作..但是没有任何想法吗?
完整代码:
exports.resize = async (req, res, next) => {
// check if there is no new file to resize
if (!req.file) {
next(); // skip to the next middlewaree
return;
}
const extension = req.file.mimetype.split('/')[1]
req.body.photo = `${uuid.v4()}.${extension}`
// now we resize
const photo = await jimp.read(req.file.buffer)
await photo.cover(300, 300);
AWS.config.update({
secretAccessKey: process.env.SECRETACCESSKEY,
accessKeyId: process.env.ACCESSKEYID,
region: 'us-east-1'
})
const s3 = new AWS.S3()
const params = {
Bucket: 'jamsession-images',
Key: req.body.photo,
// this line seems to be the issue..
// even though photo.bitmap.data its also a buffer
Body: photo.bitmap.data
};
s3.upload(params, function (err, data) {
if (err) {
console.log('%%%%%%%%%%%%%%% error in callback');
console.log(err);
}
console.log('****************** success');
console.log(data);
});
// await photo.write(`./public/uploads/${req.body.photo}`);
// once we have written the photo to our filesystem, keep going!
next()
};
答案 0 :(得分:1)
我也有这个问题,为了获得正确的结果图像缓冲区,我们必须使用Jimp的getBuffer函数。
image.getBuffer(mime, cb);
支持的MIME类型
Jimp.MIME_PNG; // "image/png"
Jimp.MIME_JPEG; // "image/jpeg"
Jimp.MIME_BMP; // "image/bmp"
但是使用Jimp.AUTO可以拥有原始图像的哑剧类型并使用它。
您可以在https://www.npmjs.com/package/jimp中阅读更多getBuffer函数
photo.getBuffer(Jimp.AUTO, function(error, result){
const params = {
Bucket: 'jamsession-images',
Key: req.body.photo,
// correct buffer
Body: result
};
s3.upload(...);
});