在Nodejs中使用jimp包裁剪一个base64格式图片时出错。

5
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)

有没有办法在Node.js中裁剪Base64格式的图像而无需将其转换为图像?

1个回答

13

问题出在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是

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接