Converting image to base64 javascript

Convert An Image To A DataURL or Base64 String Using JavaScript

In this short tutorial we explore 3 different JavaScript methods to convert an image into a Base64 string. We look at converting a File object or Blob, a canvas element, and an image tag.

In all examples below we assume we already have a , , File , or Blob object available.

We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string.

const getBase64StringFromDataURL = (dataURL) => dataURL.replace('data:', '').replace(/^.+,/, '');

Image is a File object or Blob

When the image is a File object or Blob we can use the FileReader API please see this article on converting a file to base64 string or dataURL.

Читайте также:  Html radio with text input

Image is a Canvas element

If we have a that we want to turn into a Base64 string we can use toDataURL on the Canvas element.

canvas width="300" height="150" id="my-canvas">canvas> script> const canvas = document.getElementById('my-canvas'); // Convert canvas to dataURL and log to console const dataURL = canvas.toDataURL(); console.log(dataURL); // Logs data:image/png;base64,wL2dvYWwgbW9yZ. // Convert to Base64 string const base64 = getBase64StringFromDataURL(dataURL); console.log(base64); // Logs wL2dvYWwgbW9yZ. script>

By default the canvas outputs to a lossless PNG, we can pass ‘image/png’ , ‘image/jpeg’ or ‘image/webp’ to the toDataURL method to get a different format.

When using ‘image/jpeg’ or ‘image/webp’ we can pass the image compression as the last argument, 0 means a lot of compression, 1 means no compression.

canvas width="300" height="150" id="my-canvas">canvas> script> const canvas = document.getElementById('my-canvas'); // Convert canvas to dataURL and log to console const dataURL = canvas.toDataURL('image/jpeg', 0.5); console.log(dataURL); // Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ. // Convert to Base64 string const base64 = getBase64StringFromDataURL(dataURL); console.log(base64); // Logs wL2dvYWwgbW9yZ. script>

Image is an img element

If our image is an element we can fetch the image src and convert that to a Base64 string.

Alternatively we can draw the image to a canvas and then convert the canvas to an image element, this would be useful if we’re looking for a specific image format.

If the image is located on a remote server the CORS configuration of the remote server must allow our local script to access the image.

Fetching the image source

Note that the MIME type returned by remote server in the Content-Type response header is reflected in the DataURL.

If the MIME type is incorrect the DataURL will be incorrect as well.

img src="my-image.jpeg" id="my-image" /> script> const image = document.getElementById('my-image'); // Get the remote image as a Blob with the fetch API fetch(image.src) .then((res) => res.blob()) .then((blob) =>  // Read the Blob as DataURL using the FileReader API const reader = new FileReader(); reader.onloadend = () =>  console.log(reader.result); // Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ. // Convert to Base64 string const base64 = getBase64StringFromDataURL(reader.result); console.log(base64); // Logs wL2dvYWwgbW9yZ. >; reader.readAsDataURL(blob); >); script>

Drawing the image to a canvas

Drawing the image to a canvas first allows us to convert it to a different format.

Please note that this approach is slower than simply fetching the image src as shown in the previous example.

An additional caveat is that the canvas element has a maximum size, for some browsers this size limit is very low causing problems when converting the image.

img src="my-image.jpeg" id="my-image" /> script> const image = document.getElementById('my-image'); const toDataURL = () =>  const canvas = document.createElement('canvas'); // We use naturalWidth and naturalHeight to get the real image size vs the size at which the image is shown on the page canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; // We get the 2d drawing context and draw the image in the top left canvas.getContext('2d').drawImage(image, 0, 0); // Convert canvas to DataURL and log to console const dataURL = canvas.toDataURL(); console.log(dataURL); // logs data:image/png;base64,wL2dvYWwgbW9yZ. // Convert to Base64 string const base64 = getBase64StringFromDataURL(dataURL); console.log(base64); // Logs wL2dvYWwgbW9yZ. >; // If the image has already loaded, let's go! if (image.complete) toDataURL(image); // Wait for the image to load before converting else image.onload = toDataURL; script>

Wrapping up

We converted a File , Blob , , and to DataURLs and we looked at how to convert a DataURL to a Base64 string. By looking at different methods to convert images to Base64 strings we now know the pros and cons of each approach.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

At PQINA I design and build highly polished web components.

Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.

Источник

How to Convert Images to Base64 Data URLs in JavaScript

It’s easy to convert JPG and PNG images to Base64 data URLs with JavaScript. Let me show you how. In case you didn’t know, a data URL is simply a long string of characters that represent the binary of your image. You can then use this URL in your HTML tags. Very convenient.

Video Tutorial

If you prefer a video tutorial, you can watch this 4 minute video on my YouTube channel:

Step 1. File Input

Step 2. Change Event

const fileInput = document.getElementById("fileInput"); fileInput.addEventListener("change", e =>  console.log(e); >); 

If you choose a file and check the console, you’ll notice the event object. Take note of the target.files property.

Step 3. File Reader Setup

Next, you’ll need to get a reference to the selected file and create a new instance of FileReader . This file reader object can read files in different forms.

fileInput.addEventListener("change", e =>  const file = fileInput.files[0]; const reader = new FileReader(); >); 

Step 4. Read as Data URL

reader.addEventListener("load", () =>  // Base64 Data URL 👇 console.log(reader.result); >); reader.readAsDataURL(file); 

As you can see we attach the load event to the FileReader . Once the file has finished being read, we can grab the Data URL by accessing reader.result .

Full Code

const fileInput = document.getElementById("fileInput"); fileInput.addEventListener("change", e =>  const file = fileInput.files[0]; const reader = new FileReader(); reader.addEventListener("load", () =>  // Base64 Data URL 👇 console.log(reader.result); >); reader.readAsDataURL(file); >); 

Done! Feel free to use this Data URL in your tags. Just don’t make the images too large 😎

Enrol Now 👉 JavaScript DOM Crash Course

Course Thumbnail

If you’re learning web development, you can find a complete course on the JavaScript DOM at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Источник

How to Convert the Image into a Base64 String Using JavaScript

There are several approaches in JavaScript that can help you with converting the image into a Base64 string.

Canvas

Firstly, create a canvas, then load the image into it and use toDataURL() to get the Base64 representation. In fact, it is a data URL, but it contains the Base64-encoded image:

w3docs logo

Javascript create canvas convert the image into a Base64

This can only be useful if you don’t need the original Base64 string or original image type. Be aware that this method may return different results for the same image depending on the browser and operating system. It will return not only different Base64 values but also different images.

FileReader

Firstly, load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a dataURL:

w3docs logo

Javascript use the FileReader API to convert it to a dataURL

function toDataURL(url, callback) < let xhRequest = new XMLHttpRequest(); xhRequest.onload = function () < let reader = new FileReader(); reader.onloadend = function () < callback(reader.result); >reader.readAsDataURL(xhRequest.response); >; xhRequest.open(‘GET’, url); xhRequest.responseType = ‘blob’; xhRequest.send(); > toDataURL(‘https://www.avatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0’, function (dataUrl) < console.log('RESULT:', dataUrl) >)

This approach has better compression and works for other file types as well.

Images from the local file system

If you need to convert images from the user’s file system, you should use the FileReader API:

html> html> head> title>Title of the document title> head> body> input type="file" onchange="encodeImageFileAsURL(this)" /> script> function encodeImageFileAsURL(element) < let file = element.files[0]; let reader = new FileReader(); reader.onloadend = function( ) < document.write('RESULT: ', reader.result); > reader.readAsDataURL(file); > script> body> html>

The FileReader object allows web apps to read the contents of files stored on the user’s computer asynchronously, using File or Blob objects to specify the file or data to read.

BookDuck

  • How to Convert JavaScript String to be All Lowercase and Vice Versa
  • How to Encode and Decode Strings with Base64 in JavaScript
  • How to Convert a Unix Timestamp to Time in JavaScript
  • How to Convert Decimal to Hexadecimal in JavaScript
  • How to Convert a Comma-Separated String into Array
  • How to Convert a Number to a String in JavaScript
  • How to Convert String to Title Case with JavaScript
  • How to Convert a String into a Date in JavaScript
  • How to Convert String to Number in JavaScript
  • How to Convert RGB to Hex and Vice Versa
  • How to Convert a JavaScript Date to UTC
  • How to Convert Object to String
  • How to Compare Strings in Java
  • JavaScript Blob
  • JavaScript File and FileReader
  • Canvas
  • JavaScript Strings

Источник

Convert an Image Into Base64 String Using JavaScript

Convert an Image Into Base64 String Using JavaScript

  1. Use canvas to Convert Image to Base64 String in JavaScript
  2. Use FileReader to Convert Image to Base64 String in JavaScript

JavaScript has the convention to convert an image URL or image from a local PC to a base64 string. This string can have a wide number of symbols and letters.

We will discuss creating a canvas element, loading the image into it, and using toDataURL to show the string representation. We will also try the file reader option to get the base64 string representation.

Use canvas to Convert Image to Base64 String in JavaScript

In this case, we create a canvas element and define its dimensions — the dataURL where we will store the string representation.

We will add random images from online sources, and to avoid security issues, we will ensure the object.crossOrigin = ‘Anonymous’ . Lastly, our callback function will take the dataURL to the toDataURL function to alert the window to preview the base64 string for the corresponding image.

 html lang="en">  head>  title>Testtitle>  style>  img  height: 200px;  >  style>  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> 

Use canvas to Convert Image to base64 String in JavaScript

Use FileReader to Convert Image to Base64 String in JavaScript

For a file reading convention, we will dynamically initialize a new object. The object will trigger the onload method and draw out the base64 string. Our input element is taking images from the local computer through upload.

 html lang="en"> head>  head> body>  input type="file" name="" id="fileId"  onchange="Uploaded()">  br>br>  button onclick="display()">  Display String  button>  body>  html> 
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); > 

Use FileReader to Convert Image to base64 String using JavaScript

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

Related Article — JavaScript Image

Related Article — JavaScript Base64

Copyright © 2023. All right reserved

Источник

Оцените статью