Convert image to Base64 in JavaScript
To convert image to Base64 and get the original Base64 string, I highly recommend using one of the following methods:
Of course, we can use new Image()
to draw a canvas
and using the toDataURL()
method to get the Base64 string. But this can only be useful if you don’t need the original Base64 string and/or original image type. Also keep in mind that this method may return different results for the same image depending on the browser and operating system (you can get not only different Base64 values, but also slightly different images). If this is your case or you don’t worry about it, check the example below (it is supported by most popular browser, such as Chrome 4+, Edge 12+, Firefox 3.6+, Internet Explorer 9+, Safari 4+).
// To bypass errors (“Tainted canvases may not be exported” or “SecurityError: The operation is insecure”)
// The browser must load the image via non-authenticated request and following CORS headers
var img = new Image();
img.crossOrigin = 'Anonymous';
// The magic begins after the image is successfully loaded
img.onload = function () {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
// Unfortunately, we cannot keep the original image type, so all images will be converted to PNG
// For this reason, we cannot get the original Base64 string
var uri = canvas.toDataURL('image/png'),
b64 = uri.replace(/^data:image.+;base64,/, '');
console.log(b64); //-> "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=="
};
// If you are loading images from a remote server, be sure to configure “Access-Control-Allow-Origin”
// For example, the following image can be loaded from anywhere.
var url = '//static.base64.guru/uploads/images/1x1.gif';
img.src = url;
Comments (22)
I hope you enjoy this discussion. In any case, I ask you to join it.
Access to image at '*/img_1.png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
GET */img_1.png net::ERR_FAILED
What do with that?
https://lh3.googleusercontent.com/lr/AHRh2pbpx0h3j4w089K6_JChmuqj80Roo703nkDTQvwiIbNh6WhUVG7ABVCI1hBAdKu3QOJyQJf3pjTJATmhJBMiXAqYZwlDp9fGWGUbUM0c5cDDggy3JrxSQr8oVYfIC5LZijIeno4gIustwOGpvTd8GM_Z06xZpga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