Cumulo Nimbus
Cumulo Nimbus

Reputation: 9685

Image Data to Blob from XMLHttpRequest

I am making an XMLHttpRequest:

request = new XMLHttpRequest();
request.open('GET', modifiedImageUrl, true);
request.onreadystatechange = ->
    if request.readyState == 4
        if request.status == 200
            blob = new Blob([request.response], { type: 'image/jpeg' })
request.send(null);

(Please excuse my coffeescript). I would like to create a Blob from the retrieved image, but am not getting any data in my blob besides the size and type:

Blob
    size: 88804
    type: "image/jpeg"
    > __proto__: Object

Looking at request.response:

Response (screenshot of data displayed as text)

What is this format? How can I go about converting this to a Blob that has more information than just the size?

Upvotes: 1

Views: 909

Answers (2)

ekene
ekene

Reputation: 301

It turns out the data is being decoded as ASCII when you don't specify a responseType. So for every character greater than 127, you get a 253, thus the image gets corrupted. To avoid this add overrideMimeType with charset=x-user-defined.

request = new XMLHttpRequest();
request.overrideMimeType('image/gif; charset=x-user-defined');
request.open('GET', modifiedImageUrl, true);
request.onreadystatechange = () => {
    if (request.readyState == 4)
        if (request.status == 200)
            blob =  = new Blob([Uint8Array.from(request.response, c => c.charCodeAt(0)).buffer], { type: "image/gif" });

}
request.send(null);

Upvotes: 0

Musa
Musa

Reputation: 97672

The blob has the data in it, you just can't view it like that.
Also if you didn't set your response type to arraybuffer(or blob) you image data is going to get corrupted.

Upvotes: 1

Related Questions