I'm loading a jpeg image from my server in binary format via XMLHttpRequest (I need it that way). It's not base64 encoded.
我正在通過XMLHttpRequest從服務器以二進制格式加載jpeg圖像(我需要這樣做)。這不是base64編碼。
Is it possible to turn it to an img object with javascript?
是否可以用javascript將其轉換為img對象?
Thanks
謝謝
4
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.
如果XMLHttpRequest的字符編碼設置的東西不會改變二進制數據,或者你設置響應類型,可以通過運行.responseText btoa(把它base64,讓你把它作為一個數據URI)或訪問.response二進制數據,分別。
Assuming your instance is named xhr
and you're using the charset method before xhr.send
but after xhr.open
do
假設實例名為xhr,並在xhr之前使用charset方法。發送但xhr之后。開做
xhr.overrideMimeType("text/plain; charset=x-user-defined");
then when you're 200 OK
當你200歲的時候
var dataURI = 'data:image/jpeg;base64,' + btoa(xhr.responseText);
Which you can then set as a src of an <img>
.
然后可以將其設置為的src。
Again assuming xhr
, this time .response
method; between .open
and .send
,
假設xhr,這次。response方法;.open和.send之間,
xhr.responseType = "arraybuffer";
Then at 200 OK
然后在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);
Which you can then set as a src of an <img>
. Example
然后可以將其設置為的src。例子
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/12/10/fed044a7931c0efd5491f04703ca5b2f.html。