Converting images to a Base64 data URL using Javascript

JavascriptObject Oriented ProgrammingProgramming

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, it is created as a canvas element 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 1

The following example tries to convert 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>

Example 2

Following is an example which converts an image to the URL −

<!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> <script> var base64String = ""; function Uploaded() { var file = document.querySelector( 'input[type=file]')['files'][0]; var reader = new FileReader(); reader.onload = function () { base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); imageBase64Stringsep = base64String; } reader.readAsDataURL(file); } function display() { console.log("Base64String about to be printed"); alert(base64String); } </script> </head> <body> <input type="file" name="" id="fileId" onchange="Uploaded()"> <br><br> <button onclick="display()"> Display String </button> </body> </html>
raja
Updated on 26-Aug-2022 11:53:01

Advertisements