Skip to content

Instantly share code, notes, and snippets.

@kriserickson
Last active December 31, 2015 20:59
Show Gist options
  • Save kriserickson/8044290 to your computer and use it in GitHub Desktop.
Save kriserickson/8044290 to your computer and use it in GitHub Desktop.
Using Ajax instead of getBase64Image to load images... See: http://jsfiddle.net/ksoncan34/DQYR2/3/
// See: http://jsfiddle.net/ksoncan34/DQYR2/3/
// Get an objectURL with an ajax object...
function getAjaxObjectUrl(url, callback, error) {
var xhr = new XMLHttpRequest(),
blob, objectURL, arrayBufferView;
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
var arrayBufferView = new Uint8Array(xhr.response);
var blob = new Blob([arrayBufferView], {
'type': 'image\/jpeg'
});
callback(window.URL.createObjectURL(blob));
} else {
error('Failed to load image, xhr.status: ' + xhr.status);
}
});
xhr.send();
}
// Get a dataurl from an ajax object...
function getAjaxDataUrl(url, callback, error) {
var xhr = new XMLHttpRequest(),
arrayBufferView;
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
var arrayBufferView = new Uint8Array(xhr.response);
var base64Data = btoa(String.fromCharCode.apply(null, arrayBufferView));
callback('data:image/png;base64,' + base64Data);
} else {
error('Failed to load image, xhr.status: ' + xhr.status);
}
});
xhr.send();
}
function dataUrlToBlob(dataUrl) {
var raw = window.atob(dataUrl);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
var blob2 = new Blob([array], { 'type': 'image\/jpeg' });
return window.URL.createObjectURL(blob2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment