你好,我需要从我的服务器请求一个图像(二进制、数组缓冲器),然后我想将该数组缓冲器转换为有效的imageData,以便在任何画布元素上绘制。
除了来自ajax请求的imageData之外,我还有其他的imageData对象,我将它们组合在一起放在画布上(为了压平图像)并生成我的最终图像。然而,如上所述来自服务器请求的imageData结果纯粹是噪音,我不确定我做错了什么来创建有效的imageData。
这是我的方法,试图将数组缓冲器转换为imageData,但没有成功。
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;
};
提示: 我已经成功将arrayBuffer转换为b64图像资源URL,然后将其创建为图像,并将其绘制到画布元素上,但我对这种解决方案不感兴趣,因为:
在我看来有点过度设计
使用回调函数
更新
服务器上的图像是.png文件(RGBA)。
以下是使用jQuery中的ajaxTransport进行二进制 - arraybuffer请求从服务器获取图像的代码:
$.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();
}
};
}
});