Unable To Produce Image From Base64 In Nodjs
Solution 1:
JFIF
suggests you're actually converting a .jpg file, not a .png.
Make sure the file type (e.g. .png) matches the Mime type (e.g. "image/png").
Also consider specifying charset.
SUGGESTED CHANGE:
base64Image = new Buffer.from(res1.body).toString('base64');
console.log("data:image/jpeg;charset=utf-8;base64," + base64Image;)
<= Assuming it's really a jpeg file
Don't forget to make the corresponding change in your HTML, too...
Solution 2:
when you try to do only get a request without specifying the encoding type for an image which is coming from the third party, then the response of the body will be the raw data which you are getting in bytearray variable , so you have add header encoding: "binary"
so the response will come in binary format and then you use Buffer
and BUffer.from
to convert that binary data to base64 and use it in your <img src"data:image/png;base64,yourbase64data"
functiongetImage(imageUrl) {
var options = {
url: `${imageUrl}`,
encoding: "binary"
};
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
var prefix = "data:" + resp.headers["content-type"] + ";base64,";
var img = newBuffer(body.toString(), "binary").toString("base64");// var img = new Buffer.from(body.toString(), "binary").toString("base64");
dataUri = prefix + img;
console.log(dataUri);
}
})
}
when use promise
functiongetImage(imageUrl) {
var options = {
url: `${imageUrl}`,
encoding: "binary"
};
returnnewPromise(function (resolve, reject) {
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
var prefix = "data:" + resp.headers["content-type"] + ";base64,";
var img = newBuffer(body.toString(), "binary").toString("base64");// var img = new Buffer.from(body.toString(), "binary").toString("base64");
dataUri = prefix + img;
console.log(dataUri);
resolve(dataUri);
}
})
})}
there is one node module also for this form where i got the solution https://www.npmjs.com/package/imageurl-base64
if you want to read the image form your local disk the fs
module help you
varprefix="data:"+"content-type"+";base64,";
img: fs.readFileSync(`pathtothelocalimage`, 'base64')
//img: fs.readFile(`pathtothelocalimage`, 'base64')
dataUri =prefix+ img;
Post a Comment for "Unable To Produce Image From Base64 In Nodjs"