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();
xhr.open('GET', location.href, true);
xhr.responseType = 'blob';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
reader.addEventListener('load', function (e) {
location.href = e.target.result;
});
var responseWithMimeType = new Blob(new Array(xhr.response), {
'type': xhr.getResponseHeader('Content-Type')
});
reader.readAsDataURL(responseWithMimeType);
}
});
xhr.send();
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 http://chris.zarate.org/bookmarkleter to obtain the following result:
javascript:(function(){var%20xhr=new%20XMLHttpRequest(),reader=new%20FileReader();xhr.open('GET',location.href,true);xhr.responseType='blob';xhr.addEventListener('load',function(){if(xhr.status===200){reader.addEventListener('load',function(e){location.href=e.target.result;});var%20responseWithMimeType=new%20Blob(new%20Array(xhr.response),{'type':xhr.getResponseHeader('Content-Type')});reader.readAsDataURL(responseWithMimeType);}});xhr.send();})();
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>
<html>
<head>
<title>File to Data URL</title>
</head>
<body>
<form>
<input type="file">
</form>
<script>
var file = document.querySelector('input[type=file]'), reader = new FileReader();
file.addEventListener('change', function(e) {
reader.readAsDataURL(e.target.files[0]);
});
reader.addEventListener('load', function(e) {
location.href = e.target.result;
});
</script>
</body>
</html>