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
<canvas>
,
<img>
,
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.
If we have a
<canvas>
that we want to turn into a Base64 string we can use
toDataURL
on the Canvas element.
<canvaswidth="300"height="150"id="my-canvas"></canvas><script>const canvas = document.getElementById('my-canvas');// Convert canvas to dataURL and log to consoleconst dataURL = canvas.toDataURL();
console.log(dataURL);// Logs data:image/png;base64,wL2dvYWwgbW9yZ...// Convert to Base64 stringconst 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.
<canvaswidth="300"height="150"id="my-canvas"></canvas><script>const canvas = document.getElementById('my-canvas');// Convert canvas to dataURL and log to consoleconst dataURL = canvas.toDataURL('image/jpeg',0.5);
console.log(dataURL);// Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...// Convert to Base64 stringconst base64 =getBase64StringFromDataURL(dataURL);
console.log(base64);// Logs wL2dvYWwgbW9yZ...</script>
Image is an img element
If our image is an
<img>
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.
<imgsrc="my-image.jpeg"id="my-image"/><script>const image = document.getElementById('my-image');// Get the remote image as a Blob with the fetch APIfetch(image.src).then((res)=> res.blob()).then((blob)=>{// Read the Blob as DataURL using the FileReader APIconst reader =newFileReader();
reader.onloadend=()=>{
console.log(reader.result);// Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...// Convert to Base64 stringconst 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.
<imgsrc="my-image.jpeg"id="my-image"/><script>const image = document.getElementById('my-image');consttoDataURL=()=>{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 consoleconst dataURL = canvas.toDataURL();
console.log(dataURL);// logs data:image/png;base64,wL2dvYWwgbW9yZ...// Convert to Base64 stringconst 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 convertingelse image.onload = toDataURL;</script>
Wrapping up
We converted a
File
,
Blob
,
<canvas>
, and
<img>
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