Creating image from base64 string in NodeJS

爷,独闯天下 提交于 2019-12-04 04:04:09

The problem was in the treatment on NodeJS, and I didn't doubt the code since it was the same every where with people commenting that its worked for them, nothing were different so I didn't doubt the process, but either something done wrong.

When checking it in my PHP script I've found a step that is not in the NodeJS code, and here is the PHP code:

$img = $_POST[ 'image' ];

$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);

$data = base64_decode($img);
$file = "./". uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

The difference is here: str_replace(' ', '+', $img);

I don't know how it worked for others, but for me replacing EVERY space in the base64 by + solved my problem.


New NodeJS code

req.body.image = req.body.image.replace(/^data:image\/\w+;base64,/, "");
req.body.image = req.body.image.replace(/ /g, '+');
console.log( req.body.image );

var buff = new Buffer(req.body.image, 'base64');
fs.write(fd, buff, 0, buff.length, 0, function(err,written){
    console.log( ">> "+ err );
    fs.closeSync( fd );
});

I hope this will help someone else


A better version of the code:

req.body.image = req.body.image.replace(/^data:image\/jpeg+;base64,/, "");
req.body.image = req.body.image.replace(/ /g, '+');

fs.writeFile('./records/'+model+'/out.jpeg', req.body.image, 'base64', function(err) {
    console.log(err);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!