Explain Codes LogoExplain Codes Logo

How to download a base64-encoded image?

javascript
blob-fu
base64
download
Nikita BarsukovbyNikita Barsukov·Jan 2, 2025
TLDR
function fastBase64Download(base64Data, filename) { const link = document.createElement('a'); link.href = base64Data; link.download = filename; // Adding the stealthy ninja element to the page... document.body.appendChild(link); // The click - silent and deadly... link.click(); // The ninja retires unseen... document.body.removeChild(link); } // High-quality base64 image data required! Beware of any fakes! fastBase64Download('base64ImageData', 'yourMasterpiece.png');

Now behold! A mere function, fastBase64Download, translates base64-encoded strings into a masterpiece at the speed of light! All you need are two ingredients - base64Data & filename. Watch as it gracefully clicks the invisible link to download your image.

Going vintage: supporting old browsers

In the world of browsers, "old is gold" may not hold. Lesser mortals may lack support for the download attribute. But fret not! We have ways:

function doesBrowserSupportDownload() { const a = document.createElement('a'); return typeof a.download !== 'undefined'; }

Clap your hands once if the download attribute is supported. If not (undefined), your image will open up in a new tab/window. It's time to go old school and save images manually. Charm, isn't it?

Code ninja: clicking without linking

While our ninja technique does the job, sometimes even a ninja needs an upgrade. Prepare for Blob fu - no need to insert elements to your DOM anymore!

function base64ToBlob(base64Data, mimeType) { // Slicing the base64 as we would, sushi... const byteChars = atob(base64Data.split(',')[1]); const byteArrs = []; for (let offset = 0; offset < byteChars.length; offset += 512) { const slice = byteChars.slice(offset, offset + 512); const byteNums = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNums[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNums); byteArrs.push(byteArray); } // Blob... We meet again! return new Blob(byteArrs, { type: mimeType }); } function downloadBlob(blob, filename) { // Master Wayne, your downloadable link, courtesy of Mr. Blob const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename || 'randomArt.png'; // The blob silently morphs into a file... link.click(); // Clean getaway blob; we don't leave traces. setTimeout(() => URL.revokeObjectURL(url), 100); }

Now perform Blob fu with two elements: the Blob created from the base64 image data and a filename.

Going large: dealing with big images

Facing gigantic images? Fear no more. You can fall back to the art of Canvas! It gracefully transforms your base64 image data into a Blob using canvas.toBlob. It's optimized for large images, and allows you to control the image format and quality.

function downloadCanvasAsImage(canvasElement, filename) { canvasElement.toBlob((blob) => { downloadBlob(blob, filename); }); }

Make sure your image is already on the canvas. Plus, it's an excellent trick to have up your sleeve when dealing with file size and image quality.

Making life easier with npm packages

The FileSaver npm package is a handy toolbox for developers. It simplifies the process of saving files:

import { saveAs } from 'file-saver'; function downloadBase64AsFile(base64Data, filename) { const blob = base64ToBlob(base64Data, 'image/png'); // saveAs saves your day (and the hassle)! saveAs(blob, filename); }

Must remember: saveAs simplifies file savings, making code less cryptic and more maintainable.

Playing detective: MIME types matter

Choose your agents (a.k.a MIME types) wisely! Whether it's image/png, image/jpeg, or image/svg+xml, the right MIME type ensures the image gets saved with accurate specifications:

data:[<MIME-type>];base64,<data>