简体   繁体   English

将图像缓冲区转换回 base64 时的错误

[英]Bug when converting image buffer back to base64

I am getting a strange bug where, when I convert a base64 string to an image buffer ( Buffer.from(image, "base64") ) and back to base64 ( .toString("base64") ) the resulting base64 string is missing its formatting ( dataimage/pngbase64 instead of data:image/png;base64 ) as well as missing g== at the end.我遇到了一个奇怪的错误,当我将 base64 字符串转换为图像缓冲区( Buffer.from(image, "base64") )并返回到 base64 ( .toString("base64") )时,生成的 base64 字符串丢失了它格式( dataimage/pngbase64而不是data:image/png;base64 )以及最后缺少g== This results in the image being "corrupt" and not rendering when I put it in an <img /> in the frontend.这会导致图像“损坏”并且当我将它放在前端的<img />中时不会呈现。 The current workaround I'm using is the following:我正在使用的当前解决方法如下:

image.toString("base64").replace("dataimage/pngbase64", "data:image/png;base64,") + "g=="

but this is far from an optimal solution and I would like to not use this sort of workaround.但这远非最佳解决方案,我不想使用这种解决方法。

This is where I bufferize the image ( image is base64) and store it in the database这是我缓冲图像( image是 base64)并将其存储在数据库中的地方

t.field("createModel", {
  type: $name,
  args: { input: nonNull(arg({ type: createModelInput.name })) },
  resolve: async (_, args) => {
    const { image, name, manufacturerId, identifiers } = args.input;

    console.log(image) // correct base64 image from frontend
    const buffedImage = Buffer.from(image, "base64");
    console.log(buffedImage.toString("base64")) // not the same as image above: missing formatting & g== at the end

    return await prisma.model.create({
      data: {
        image: buffedImage,
        name,
        identifiers,
        manufacturer: {
          connect: {
            id: manufacturerId,
          },
        },
      },
    });
  },
});

Please tell me any further information is needed.请告诉我需要任何进一步的信息。

The Base64 part of the string doesn't start until after the , ;字符串的Base64编码部分没有启动,直到后, ; the data: part is a scheme, the image/png part is a content type, and the base64, part is an indicator that what follows it is Base64 encoded text.data:部分是一个方案中, image/png部分是一个内容类型和base64,部分是一个指标,接下来它是Base64编码文本。 So you're asking to convert non-Base64 data when you try to use that entire string as Base64.因此,当您尝试将整个字符串用作 Base64 时,您要求转换非 Base64 数据。

You have to remove that prefix first, because it's not part of the Base64 data.必须先删除该前缀,因为它不是 Base64 数据的一部分。 It's just part of the data: URI.它只是data:的一部分data: URI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM