You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jimp报错Could not find MIME for Buffer<null>跨服务器图片传输问题求解

错误原因
  • 服务器B返回数据不符合图片格式要求:image.bitmap.data仅存储纯RGBA像素序列,没有标准图片格式(JPG/PNG等)必备的文件头、元数据信息,Jimp无法识别这类无格式的像素数据对应的MIME类型。
  • 服务器A的数据解析逻辑完全错误:一是axios默认将返回值按JSON格式解析,拿到的response.data本身就已经是损坏的二进制数据;二是额外对二进制数据执行JSON.stringify操作后再转Buffer,直接彻底破坏了原始二进制结构,导致传入Jimp的Buffer属于无效数据。
修复方案

服务器B代码修改

将直接返回bitmap数据的逻辑,改为先将处理后的图片转成标准格式的Buffer再返回,同时设置正确的响应头,示例修改如下:

app.post('/image', (req, res) => {
  Jimp.read(Buffer.from(req.body.buffer.data))
    .then(image => {
      axios.get('https://geek-jokes.sameerkumar.website/api?format=json').then(function (response) {
            Jimp.loadFont(Jimp.FONT_SANS_64_WHITE).then(font => {
              const width = image.bitmap.width;
              const height = image.bitmap.height;
              image.print(font, width * 20 / 100, height * 80 / 100, response.data.joke);
              // 替换原res.send(image.bitmap.data)的逻辑
              image.getBuffer(Jimp.MIME_JPEG, (err, buffer) => {
                if (err) {
                  console.log(err);
                  return res.status(500).send('处理失败');
                }
                res.setHeader('Content-Type', Jimp.MIME_JPEG);
                res.send(buffer);
              })
            });
        }).catch(function (error) {
                console.error('Error ' + error.message)
            })
    }).catch(err => {
    console.log(err)
  });
})

服务器A代码修改

首先给axios请求添加responseType: 'arraybuffer'配置,告知axios直接返回原始二进制Buffer,不要做JSON解析;其次删除错误的JSON.stringify处理逻辑,直接用返回的Buffer传入Jimp即可,示例修改如下:

const imgUpload = (req, res) => {
    const byteContent = req.file
    if (byteContent) {
        axios.post('http://127.0.0.1:4000/image',
            byteContent, {
              responseType: 'arraybuffer' // 新增配置项
            }).then(function (response) {
                // 直接用response.data即可,无需额外处理
                Jimp.read(response.data)
                    .then(image => {
                        image.write('public/uploads/aja.jpg')
                    }).catch(function (error) {
                        console.error('Error ' + error.message)
                    })
            }).catch(err => {
                console.log(err)
            });
    } else {
        res.send('Something went wrong :c')
    }
}

内容的提问来源于stack exchange,提问作者Clown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:18:02