我正在开发一个节点+ express后端。
我从API接收base64图像字符串,我将其存储到MongoDB中。在存储之前我想减小图像大小(缩放)。我试过JIMP,但它没有读取base64输入。
任何人都可以建议任何接受base64图像的好节点模块,缩放它并返回一个新的base64字符串。
由于
答案 0 :(得分:0)
有点晚了,但是我只是使用sharp
库实现了此功能,所以不妨现在就共享它。
我创建了一个函数,该函数采用base64
以及您要将图像调整大小的高度和宽度(可选),并返回调整后的base64字符串。
我随时可以调用此函数。
// Don't forget to import sharp
import sharp from "sharp"
export const resizeBase64 = async ({ base64Image, maxHeight = 640, maxWidth = 640 }) => {
const destructImage = base64Image.split(";");
const mimType = destructImage[0].split(":")[1];
const imageData = destructImage[1].split(",")[1];
try {
let resizedImage = Buffer.from(imageData, "base64")
resizedImage = await sharp(resizedImage).resize(maxHeight, maxWidth).toBuffer()
return `data:${mimType};base64,${resizedImage.toString("base64")}`
} catch (error) {
throwError({ error })
}
};
答案 1 :(得分:0)
您仍然可以使用 JIMP,但您需要做的就是在读取 base64 之前去掉前缀。
根据您的图像格式,在以下示例中使用特定的 jpg 或 png。
示例:
Jimp.read(Buffer.from((yourImageBuffer).replace(/^data:image\/png;base64,/, ""), 'base64'), function (err, image) {
// Do you stuff here with the image
})
答案 2 :(得分:-1)
....some logic....
let max_width = 371;
let max_height = 280;
var image = new Image();
image.src = YOUR_BASE64_STRING;
let image_width = image.width;
let image_height = image.height;
let ratio = 1;
if(image_width > max_length || image_height > max_length){ //need to scale
ratio = max_length / image_width;
if(image_height > image_width){
ratio = max_length / image_height;
}
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = image_width * ratio; // target width
canvas.height = image_height * ratio; // target height
ctx.drawImage(image,
0, 0, image.width, image.height,
0, 0, canvas.width, canvas.height
);
var RESIZED_BASE64_STRING = canvas.toDataURL();
....some logic....