简体   繁体   English

将Base64缓冲区另存为映像到磁盘

[英]Saving Base64 Buffer as an image to the Disk

in a Node.js app, i send an image via Socket.io to the server. Node.js应用程序中,我通过Socket.io将图像发送到服务器。 in the server, i get it like this and i wanted to save it on the disk. 在服务器中,我像这样得到它,我想将其保存在磁盘上。 it save's but i cant open that image and image viewer says it's damaged! 它保存的,但是我无法打开该图像,并且图像查看器说它已损坏! file size is correct but i can't open it. 文件大小正确,但我无法打开它。 is there anything that i miss in the code? 代码中有什么我想念的吗?

    socket.on('newImage', function (data) {
       var img = data.image;
       var coded_img = new Buffer(img, 'base64');

       fs.writeFile("out.png", coded_img,'base64', function(err) {
             if (err) throw err;
             console.log('File saved.')
       });
    });

I solved it, With this function, i recovered main image data: 我解决了,通过此功能,我恢复了主要图像数据:

decodeBase64Image = function(dataString) {
    var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
        response = {};

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

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

    return response;
};

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

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