Get image data URL in JavaScript?
To convert an image to a Data URL in JavaScript, leverage the Canvas
API and the toDataURL()
function:
Remember: Ensure the cross-origin resource sharing (CORS) is handled properly for images from different domains.
Cracking the code
Image formats: don't judge a book by its MIME type
Different image formats require different handling. Check the original image format before transforming it into a Data URL. Remember, by default, toDataURL()
generates a PNG image. Change the format like this:
Note the compatibility issues with JPEG images in older Firefox versions. The time machine doesn't always work well with JPEG!
CORS: the strict border control for your images
View the crossOrigin
property as your image's passport. When dealing with images from different domains, CORS check points are a must:
Check if the hosting server supports CORS. Blocked at the border? Blame the CORS, not the image!
Making friends with Greasemonkey scripts
Greasemonkey userscripts might require some tweaks to make the Canvas
method work. Think of it like fitting a square HTML box into a circular Greasemonkey hole.
Privacy: because nobody likes stalkers
Canvas fingerprinting uses canvas data to track users. Remember, what happens on canvas, stays on canvas (privacy concerns), unless explicitly asked!
Fetch me an image, pretty please?
Fetch API
can fetch you images, not coffee. Convert a fetched blob into a Data URL as shown:
A new method in town: meet Mr. toDataURL
You can add toDataURL
method directly to HTMLImageElement
. Here's the secret handshake:
The practical side of things
Throughout your journey, remember these navigational tips:
-
Image Loading: Wait for the onload event before painting your image on the canvas.
-
Data URL Prefix: To get the raw base64 string, just slice 'n dice the Data URL prefix:
-
Re-encoding Variance: Converting image to "image/jpg" may slightly alter the image.
References
Was this article helpful?