Node.js Base64 图像解码和写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10037563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:27:28  来源:igfitidea点击:

Node.js Base64 Image decoding and writing to file

imageapache-flexnode.jsbase64decoding

提问by Mehdi

I'm sending the contents of this Flex form (Don't ask why) over to node. There is a post paramteter called "photo" which is a base64 encoded image.

我将这个 Flex 表单的内容(不要问为什么)发送到节点。有一个名为“photo”的帖子参数,它是一个 base64 编码的图像。

Contents of photo get sent over ok. Problem is when I am trying to decode the content and write them to a file.

照片内容发送完毕。问题是当我尝试解码内容并将它们写入文件时。

  var fs = require("fs");

  fs.writeFile("arghhhh.jpg", new Buffer(request.body.photo, "base64").toString(), function(err) {});

I've tried toString("binary") as well. But it seems node doesnt decode all of the content. It seems it only decodes jpg header info and leaves the rest.

我也试过 toString("binary") 。但似乎节点没有解码所有内容。似乎它只解码 jpg 标头信息并保留其余信息。

Can anyone please help me with this?

任何人都可以帮我解决这个问题吗?

Thanks

谢谢

回答by Nathan Friedly

Try removing the .toString()entirely and just write the buffer directly.

尝试.toString()完全删除并直接写入缓冲区。

回答by Placeholder

this is my full solution which would read any base64 image format, decode it and save it in the proper format in the database:

这是我的完整解决方案,它可以读取任何 base64 图像格式,对其进行解码并将其以正确的格式保存在数据库中:

    // Save base64 image to disk
    try
    {
        // Decoding base-64 image
        // Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
        function decodeBase64Image(dataString) 
        {
          var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
          var response = {};

          if (matches.length !== 3) 
          {
            return new Error('Invalid input string');
          }

          response.type = matches[1];
          response.data = new Buffer(matches[2], 'base64');

          return response;
        }

        // Regular expression for image type:
        // This regular image extracts the "jpeg" from "image/jpeg"
        var imageTypeRegularExpression      = /\/(.*?)$/;      

        // Generate random string
        var crypto                          = require('crypto');
        var seed                            = crypto.randomBytes(20);
        var uniqueSHA1String                = crypto
                                               .createHash('sha1')
                                                .update(seed)
                                                 .digest('hex');

        var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';

        var imageBuffer                      = decodeBase64Image(base64Data);
        var userUploadedFeedMessagesLocation = '../img/upload/feed/';

        var uniqueRandomImageName            = 'image-' + uniqueSHA1String;
        // This variable is actually an array which has 5 values,
        // The [1] value is the real image extension
        var imageTypeDetected                = imageBuffer
                                                .type
                                                 .match(imageTypeRegularExpression);

        var userUploadedImagePath            = userUploadedFeedMessagesLocation + 
                                               uniqueRandomImageName +
                                               '.' + 
                                               imageTypeDetected[1];

        // Save decoded binary image to disk
        try
        {
        require('fs').writeFile(userUploadedImagePath, imageBuffer.data,  
                                function() 
                                {
                                  console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
                                });
        }
        catch(error)
        {
            console.log('ERROR:', error);
        }

    }
    catch(error)
    {
        console.log('ERROR:', error);
    }

回答by Diego Alberto Zapata H?ntsch

In nodejs 8.11.3 new Buffer(string, encoding)is deprecated, instead of this the new way to do that is Buffer.from(string, encoding)always without .toString(). For more details read the documentation in nodejs docs: Buffer

在 nodejs 8.11.3new Buffer(string, encoding)中已弃用,取而代之的是新的方法Buffer.from(string, encoding)总是没有.toString(). 有关更多详细信息,请阅读nodejs 文档中的文档:缓冲区

回答by sam100rav

Remove .toString()

消除 .toString()

Here you decode the base64 to a buffer, which is fine, but then you convert the buffer into a string. This means that it is a string object whose code points are bytes of the buffer.

在这里,您将 base64 解码为缓冲区,这很好,但随后将缓冲区转换为字符串。这意味着它是一个字符串对象,其代码点是缓冲区的字节。