如何将 base64 编码的图像保存到磁盘?

新手上路,请多包涵

我的 Express 应用程序正在从浏览器接收 base64 编码的 PNG(使用 toDataURL() 从画布生成)并将其写入文件。但该文件不是有效的图像文件,“文件”实用程序只是将其标识为“数据”。

 var body = req.rawBody,
  base64Data = body.replace(/^data:image\/png;base64,/,""),
  binaryData = new Buffer(base64Data, 'base64').toString('binary');

require("fs").writeFile("out.png", binaryData, "binary", function(err) {
  console.log(err); // writes out file without error, but it's not a valid image
});

原文由 mahemoff 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 605
2 个回答

我认为您转换数据的次数超出了您的需要。使用正确编码创建缓冲区后,只需将缓冲区写入文件即可。

 var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

new Buffer(…, ‘base64’) 通过将输入解释为 base64 编码字符串,将输入字符串转换为 Buffer,它只是一个字节数组。然后您可以将该字节数组写入文件。

更新

正如评论中提到的, req.rawBody 不再是一个东西。 If you are using express / connect then you should use the bodyParser() middleware and use req.body , and if you are doing this using standard节点然后您需要聚合传入的 data 事件 Buffer 对象并在 end 回调中进行此图像数据解析。

原文由 loganfsmyth 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我的完整解决方案,它可以读取任何 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);
    }

原文由 Placeholder 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题