Convert Image to Data URI with JavaScript


JavaScript has a convention for converting an image URL or a local PC image to a base64 string. This string can contain a variety of symbols and letters. In here it is explained how to make a canvas element, load an image into it, and use toDataURL() to display the string representation. To obtain the base64 string representation, we will also use the file reader option.

In this case, a canvas element will be created and its dimensions will be specified. The dataURL where the string representation will be stored. We will add random images from online sources and ensure the object to avoid security issues. 'Anonymous' as crossOrigin. Finally, our callback function will pass the dataURL to the toDataURL function to notify the window that the base64 string for the corresponding image is ready for preview.

Example

This example demonstrates how to converting images to Base64 data URL in JavaScript −

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get URL i</title> </head> <body> <img src="https://images.unsplash.com/photo-1606115915090-be18fea23ec7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80" id="myImg"> <script> function toDataURL(src, callback){ var image = new Image(); image.crossOrigin = 'Anonymous'; image.onload = function(){ var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.height = this.naturalHeight; canvas.width = this.naturalWidth; context.drawImage(this, 0, 0); var dataURL = canvas.toDataURL('image/jpeg'); callback(dataURL); }; image.src = src; } toDataURL('https://images.unsplash.com/photo-1606115915090-be18fea23ec7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=465&q=80', function(dataURL){ alert(dataURL); }) </script> </body> </html>

Updated on: 26-Aug-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements