How to get the Data URL of an image in JavaScript (dog and cat picture, arrow to data url excerpt)

How to get the Data URL of an Image in JavaScript

Posted by

Overview

Lately I’ve been doing some work on an HTML file I have on my desktop, to play around with Canvas. Unfortunately, using images stored on your local machine causes some issues with Canvas. Specifically, I’ve been getting errors saying “Tainted canvases may not be exported.”. The “tainted canvas” is a result of drawing an image that violates CORS policies. To get around this issue, I have been using the data URL of the image as the image source.

What is a data url? It’s a url that represents a file’s data, with a specification of the file type. If the file is an image, navigating to the data url in Chrome specifically will result in the image being displayed. Typically, with <img> tags, you specify a hosted image url as the source. Similarly, setting the “src” attribute of <img> tags to the data url of the image displays the image.

How to get a data url

The easiest way to get a data url from an image is to load the image using a FileReader and checking the Result property. A demo is below to show how to leverage a FileReader and Canvas to get the data url of a selected image. It uses an input, and on change it updates the text box to be the data url and draws the result onto the canvas.

See the Pen Uploaded image toDataURL by Mitch Valenta (@M0tch) on CodePen.

Conclusion

As noted in the stack overflow link, there are certainly other ways to get around the Tainted Canvas error. However, leveraging the data url worked for me, mostly because I was calling canvas .toDataUrl() elsewhere in my code.

Now, just a few notes to wrap this up. First up, checking https://caniuse.com/#feat=filereader, file reader is pretty widely supported, as is Canvas, so browser compatibility should be a non-issue. Second, while you can theoretically store a data url, in a database for example, I wouldn’t recommend it if you can avoid it. Instead, it would be better to store the actual file somewhere and reference the file. Lastly, while this post details how to get a data url in Javascript, it’s not too difficult to handle data urls in, say, c# if needed.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.