从服务器加载与JavaScript的图像二值图像 [英] Binary image loaded from server to image with javascript
问题描述
我是从通过XMLHtt prequest我的二进制格式的服务器加载JPEG图像(我需要这种方式)。它没有采用base64 EN codeD。
I'm loading a jpeg image from my server in binary format via XMLHttpRequest (I need it that way). It's not base64 encoded.
是否有可能把它用JavaScript变成一个img对象?
Is it possible to turn it to an img object with javascript?
感谢
推荐答案
如果的 XMLHtt prequest
已设置为<一个字符编码href=\"https://developer.mozilla.org/en-US/docs/DOM/XMLHtt$p$pquest/Using_XMLHtt$p$pquest#Handling_binary_data\"相对=nofollow>东西,不会改变的二进制数据,或者你的设置响应类型,则可以再运行 .responseText
到 BTOA
(把它用base64,让你将其指定为数据URI)或访问 .response
的二进制数据,分别为。
If the character encoding of the XMLHttpRequest
has been set to something that won't change the binary data, or you've set the response type, you can then run .responseText
through btoa
(putting it in base64 and letting you assign it as a data URI) or access .response
for the binary data, respectively.
假设您的实例被命名为 XHR
和你正在使用的字符集方法之前 xhr.send
但经过 xhr.open
不要
Assuming your instance is named xhr
and you're using the charset method before xhr.send
but after xhr.open
do
xhr.overrideMimeType("text/plain; charset=x-user-defined");
那么,当你 200 OK
var dataURI = 'data:image/jpeg;base64,' + btoa(xhr.responseText);
然后您可以设置为的src 的的&LT; IMG方式&gt;
再次假设 XHR
,此时 .response
方法;之间的。开
和。发送
,
Again assuming xhr
, this time .response
method; between .open
and .send
,
xhr.responseType = "arraybuffer";
然后,在 200 OK
var arrayBufferView = new Uint8Array(xhr.response), // can choose 8, 16 or 32 depending on how you save your images
blob = new Blob([arrayBufferView], {'type': 'image\/jpeg'}),
objectURL = window.URL.createObjectURL(blob);
然后您可以设置为的src 的一个&LT的; IMG&GT;
。 示例
Which you can then set as a src of an <img>
. Example
这篇关于从服务器加载与JavaScript的图像二值图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!