【发布时间】:2015-04-01 07:31:40
【问题描述】:
您好,我从我的服务器(binay,arraybuffer)请求一个图像,然后我想将该 arraybuffer 转换为可以在任何画布元素上绘制的有效 imageData。
除了由 ajax 请求生成的 imageData 之外,我还有其他 imageData 对象,我将它们全部组合在画布上(为了使图像变平)并生成我的最终图像。但是,上面提到的来自服务器请求的 imageData 会产生纯噪声,我不确定我在创建有效 imageData 时做错了什么。
这是我尝试将arraybuffer转换为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;
};
PS:我已经设法将 arrayBuffer 转换为 b64 图像资源 URL,然后从中创建图像,然后将图像绘制到画布元素上,但我对这样的解决方案不感兴趣,因为:
在我看来太过分了
使用回调
更新
服务器上的图像是 .png 文件 (RGBA)。
下面是与 jQuery 一起使用的 ajaxTransport,以便对来自服务器的图像执行二进制数组缓冲区请求:
$.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();
}
};
}
});
【问题讨论】:
-
数据是原始数据还是代表文件?如果是原始的,数据是什么格式的,它是否包含 RGBA 格式的 8 位值,以什么字节顺序?
-
我已经更新了我的问题,图像是服务器上的 png 文件,我正在使用上面的 ajax Transport“插件”和 jQuery 来进行图像请求。
-
我对 png 文件感兴趣只是因为它的透明度
标签: javascript ajax html canvas