Data URI Bookmarklet

This is a repost of something I wrote on My Opera forums on 8 January 2013. The My Opera forums will be shutting down on 1 March 2014.

The easiest method [to base64 encode an image] might be to use the newly supported (since v12) FileReader object, which has a readAsDataURL method. I wrote a quick proof of concept using XHR because I’m not really sure how else to get data to it (aside from a file input which is no good here). Alternatively you could load the image in a canvas and call toDataURL, but then you’ll lose stuff like metadata and I’m not even sure if the compression and such will remain the same.

var xhr = new XMLHttpRequest(),
	reader = new FileReader();'GET', location.href, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', function () {
	if (xhr.status === 200) {
		reader.addEventListener('load', function (e) {
			location.href =;
		var responseWithMimeType = new Blob(new Array(xhr.response), {
			'type': xhr.getResponseHeader('Content-Type')

It does seem a bit roundabout, so I’d love to hear it if anyone has more efficient suggestions.

I just realized you may not be aware of how to make a bookmarklet. To save myself the effort of removing comments and such I used to obtain the following result:


Create a new bookmark, paste that into the URL and give it a nickname of your choice.

Easier still, just drag this or right-click, bookmark link: To Data URI. There might be some security restrictions on MyOpera against javascript links, so I’m not sure if it’ll work.

But for local files a simple page would do just fine. All you need is input type=”file” and a tiny bit of scripting similar to the above. Something like this should do:

<!DOCTYPE html>
<title>File to Data URL</title>

<input type="file">

var file = document.querySelector('input[type=file]'), reader = new FileReader();

file.addEventListener('change', function(e) {

reader.addEventListener('load', function(e) {
	location.href =;


Leave a Comment

You must be logged in to post a comment.