How to download a base64-encoded image?
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:
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!
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.
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:
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>
Was this article helpful?