gpt4 book ai didi

node.js - 在 Nodejs 中使用 jimp 包裁剪 base64 格式图像时出错

转载 作者:太空宇宙 更新时间:2023-11-03 22:45:12 28 4
gpt4 key购买 nike

var base64str="data:image/jpeg;base64,***"//base64 format of the image
var buf = Buffer.from(base64str, 'base64');

jimp.read(buf, (err, image) => {
if (err) throw err;
else {
image.crop(140, 50, 200, 280)
.quality(100)
.getBase64(jimp.MIME_JPEG, function(err, src) {
console.log("rb is \n")
console.log(src);
})
}
})

我尝试使用 npm 中的 jimp 包来裁剪图像的 base64 格式,但出现如下错误:

Error: Could not find MIME for Buffer <null>
at Jimp.parseBitmap (D:\Node\image-crop\node_modules\@jimp\core\dist\utils\image-bitmap.js:108:15)
at new Jimp (D:\Node\image-crop\node_modules\@jimp\core\dist\index.js:425:32)
at _construct (D:\Node\image-crop\node_modules\@jimp\core\dist\index.js:100:393)
at D:\Node\image-crop\node_modules\@jimp\core\dist\index.js:932:5
at new Promise (<anonymous>)
at Function.Jimp.read (D:\Node\image-crop\node_modules\@jimp\core\dist\index.js:931:10)
at Object.<anonymous> (D:\Node\image-crop\index.js:46:6)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)

有没有办法裁剪base64格式的图像而不将其转换为Nodejs中的图像?

最佳答案

问题出在base64字符串上。要使其正常工作,只需删除前缀 data:image/jpeg;base64,,然后保留数据即可。

示例:

const base64str = "R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="//base64 of a 1x1 black pixel
const buf = Buffer.from(base64str, 'base64');

jimp.read(buf, (err, image) => {
if (err) throw err;
else {
image.crop(140, 50, 200, 280)
.quality(100)
.getBase64(jimp.MIME_JPEG, function (err, src) {
console.log("rb is \n")
console.log(src);
})
}
})

输出是:

rb is

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA[...]

关于node.js - 在 Nodejs 中使用 jimp 包裁剪 base64 格式图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52400486/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com