mercredi 1 avril 2015

Draw ajax arraybuffer response into canvas

Hello I request an Image from my server (binay, arraybuffer) and then I would like to convert that arraybuffer to valid imageData that can be drawn on any canvas element.


Besides the imageData made from the ajax request, I also have other imageData objects which I combine all together on a canvas (in order to flatten the image) and produce my final image. However the imageData as mentioned above from the server request results in pure noise I"m not sure what I'm doing wrong to create valid imageData.


Here is my method that tries to convert the arraybuffer into imageData without success.



ImageProcessor.prototype.imageData = function(data, width, height) {

width = width || this.settings.width;
height = height || this.settings.width;

var newData = (data instanceof Uint8ClampedArray) ? data : new Uint8ClampedArray(data);
var imageData = this.ctx.createImageData(width, height);

imageData.data.set(newData);

return imageData;

};


PS: I've managed to convert the arrayBuffer into a b64 image resource-URL and then create an image out of it and then draw th image on to the canvas element, but I'm not interested in such a solution because:




  1. overkill in my opinion




  2. uses callbacks




UPDATE


The images on the server are .png files (RGBA).


And bellow is the ajaxTransport used with jQuery in order to do the binary - arraybuffer requests for images from the server:



$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
{
return {
// create new XMLHttpRequest
send: function(_, callback){
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null;

xhr.addEventListener('load', function(){
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});

xhr.open(type, url, true);
xhr.responseType = dataType;
xhr.send(data);
},
abort: function(){
jqXHR.abort();
}
};
}
});

Aucun commentaire:

Enregistrer un commentaire