Explain Codes LogoExplain Codes Logo

Browser/html Force download of image from src="data:image/jpeg;base64..."

javascript
blob
data-uri
file-saver-js
Anton ShumikhinbyAnton Shumikhin·Dec 5, 2024
TLDR

To download a base64 image from your browser, utilize an <a> tag with the download attribute. Set the href to the image data and download to your desired file name. Here is an example:

<a href="data:image/jpeg;base64,...base64 data..." download="desired-image.jpg">Download</a>

Give it a click, and voila! Instantaneous download of your image with the specified filename.

Handling various browsers and their quirks

Programming always involves being one step ahead and handling cases that slip out of the norm. Browsers have their own personalities, and to gel with all, we need to consider several edge cases and plan our strategy.

Blob: A friend for older browsers

For those old-timers who still swear by older browsers or those handling larger files, the way to extract image data is to convert the data URI to a respectable blob. This ensures smooth sailing and compatibility. Here's how you do it.

function dataURItoBlob(dataURI) { // Decode Base64 string (Imagine unscrambling a secret message!) var byteString = atob(dataURI.split(',')[1]); // Create ArrayBuffer (A fancy name for creating space for the data) var ab = new ArrayBuffer(byteString.length); // Create a buffer for holding binary data (Hey, we got some extra luggage here) var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); // Each byte contributes to the data } // Create Blob from ArrayBuffer (Blob's the name, storing's the game) var blob = new Blob([ab], {type: 'image/jpeg'}); return blob; } // Call a cab for Blob var blob = dataURItoBlob('data:image/jpeg;base64,...'); var url = URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = 'desired-image.jpg'; document.body.appendChild(a); // adding an extra passenger to the body of our HTML train a.click(); // Clean-up after Blob, we don't want a memory mess here window.URL.revokeObjectURL(url);

You now have a safer and more reliable approach to download the image across diverse environments.

Javascript strikes: Enhance your user experience

To add that extra oomph to your UX, Javascript comes into play. Here's how to let your download take off without needing the user to click a link:

window.open(url);

Alternatively, to change the current page location for direct downloads, go with:

window.location.href = url;

Both methods give your user a sense of familiarity while improving navigation.

Upgrading download attribute for guided downloads

When you want to download dynamically generated content or if your user loves surprises (no user interaction), the simple anchor tag won't do. Here comes the need to enhance the download attribute. Brace yourself for some Javascript magic and dynamic handling!

JavaScript: Alter the image before download

If the image data isn't readily available as a data URI, we can draw the image onto a canvas element, and then extract the data URI.

var canvas = document.createElement('canvas'); // Set canvas dimensions to match the image size var ctx = canvas.getContext('2d'); var img = new Image(); img.onload = function(){ ctx.drawImage(img, 0, 0); // painting the canvas with our image // Extract data URI from canvas var dataURI = canvas.toDataURL('image/jpeg'); // Convert data URI to Blob var blob = dataURItoBlob(dataURI); // Continue with creating URL and triggering download... }; img.src = 'path/of/image.jpg'; // To infinity and beyond!

Libraries for the vanishing act: FileSaver.js

FileSaver.js is a life-saver when you want to write less but get more done. This cross-browser compatible library effortlessly deals with browser-specific quirks and saves the day (and your file!).

saveAs(blob, "desired-image.jpg"); // FileSaver.js does the magic

Just a snippet of code, and your file is saved!

References