I want to convert an image to base64 from reactjs to save that image in mongo without uploading the image to the server and then converting it if not converting the image directly
Asked
Active
Viewed 1.4k times
6
-
https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – Eric Hasselbring Feb 20 '19 at 19:41
-
Possible duplicate of [How to convert image into base64 string using javascript](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) – Eric Hasselbring Feb 20 '19 at 19:41
-
https://stackoverflow.com/questions/22172604/convert-image-url-to-base64 – Benjamín Vázquez Feb 20 '19 at 19:43
1 Answers
6
I share my solution
const getEmergencyFoundImg = urlImg => {
var img = new Image();
img.src = urlImg;
img.crossOrigin = 'Anonymous';
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
var b64 = canvas.toDataURL('image/png').replace(/^data:image.+;base64,/, '');
return b64;
};
I recommend calling this function with async / await to build the object of the post.
The method extracts it from this source: https://base64.guru/developers/javascript/examples/convert-image

Ramsés López
- 461
- 7
- 8