I'm switching an implementation of a cross-site request for an image converted to base 64 from Canvas to XMLHttpRequest and FileReader, so that it can be used inside of web workers. And I want to know if there's a way to get the image width and height from the get-go.
The new function
var convertFileToDataURLviaFileReader = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
xhr.open('GET', url.replace(/^https:\/\//i, 'http://'));
xhr.send();
}
Our old Function
var convertImgToDataURLviaCanvas = function(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
var allInfo = {
data: dataURL,
width: this.width,
height: this.height
}
// Add height and width to callback
callback(allInfo);
canvas = null;
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
img.src = url.replace(/^https:\/\//i, 'http://');
}
In the old function I can just get the height and width with canvas, and I do so inside of the var allInfo
. Is there an equivalent for FileReader or some way to get the width and height inside of the new function?
To clarify, I am switching to the XMLHttpRequest
because Web Workers don't have access to the DOM, so Canvas can't be used.