Skip to content

Instantly share code, notes, and snippets.

@saintach
Created August 1, 2016 04:25
Show Gist options
  • Save saintach/2a0b2bdb3d6eedf5ff5e0879e7f9372b to your computer and use it in GitHub Desktop.
Save saintach/2a0b2bdb3d6eedf5ff5e0879e7f9372b to your computer and use it in GitHub Desktop.
Get data url of an image using xhr
var url = 'path/to/image/file' ;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// Set responseType to 'arraybuffer', we want raw binary data buffer
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
// Create an array of 8-bit unsigned integers
var arr = new Uint8Array(this.response);
// String.fromCharCode returns a 'string' from the specified sequence of Unicode values
var raw = String.fromCharCode.apply(null, arr);
//btoa() creates a base-64 encoded ASCII string from a String object
var b64 = btoa(raw);
var dataType = 'yourImageDataType';
//ta-da your image data url!
var dataURL = 'data:image/' + dataType + ';base64,' + b64;
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment