Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put png binary data into an img tag and display it as an image?

I am using this

        $.ajax({
            type: "GET",
            url: 'template/bump1/purse.png',
            datatype:"image/png",
            success: function (data) {


                var reader = new FileReader();

                reader.onload = function (e) {
                  var img = document.getElementById("CaptchaImg");
                  img.src = e.target.result;
                };
                reader.readAsDataURL(data);


                //$('#CaptchaImg').attr('src', data);
            }
         });

to download an image, and it comes out in binary, looking like this

enter image description here

node.js is returning it as

                        WriteHeaderMode('image/png', res, 200);
                        res.end(data, 'binary');

But now, how do I put that into an image tag and show it as an image. Note: I do not want to have return data as base64 encoding, it has to be binary. Im fine with converting the binary into base64 on client side though.

When I pass it to the readAsDataURL, it says TypeError exception.

Thanks

EDIT

                var img = document.getElementById("CaptchaImg");

                  var reader = new FileReader();

                  reader.onload = function(e) {
                      //img.src = e.target.result;
                      $("body").html(e.target.result);
                    };

                  reader.readAsDataURL(new Blob([data]));

this seems to convert it into a base64 encoding, which starts as data:application/octet-stream;base64, but doesn't display an image...

like image 625
sneaky Avatar asked Aug 19 '15 02:08

sneaky


4 Answers

jQuery Ajax does not support binary responses(okay now it does), there is a trick that uses overrideMimeType('text/plain; charset=x-user-defined') to return each byte as a character in the response string and then to loop through the response to create a byte array of the data.

However with bare naked XMLHttpRequest this can be done easily with use of the responseType property.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        var img = document.getElementById("CaptchaImg");
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'template/bump1/purse.png');
xhr.responseType = 'blob';
xhr.send(); 
like image 85
Musa Avatar answered Oct 24 '22 09:10

Musa


Musa's answer is a great solution, I implemented something similar in angular and works great, when you define responseType = 'blob' your response won't be a string anymore, it will be a blob type object. I just needed to add an extra parameter to the headers object (not sure if it's necessary in jQuery). headers: {'Content-Type': "image/png"}, My full request object:

var request = {
            url: "_/get_image_/get",
            method:"GET",
            headers: {'Content-Type': "image/png"},
            responseType: 'blob'
        }
like image 44
Landeta Avatar answered Oct 24 '22 10:10

Landeta


Try using new Blob(data, {type : 'image/png'}) instead of new Blob([data])

This will ensure that the media type of the blob is a png.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Blob

like image 41
Thomas Connard Avatar answered Oct 24 '22 09:10

Thomas Connard


Whatever framework/lib you're using:

  • When getting the image (a File), ask for a BLOB type
  • Use the following function to create a Blob and get an URL out of it
  • Set your image src to that URL

Code:

export function fileToImageBase64Url(file: File): string {
  const blob = new Blob([file], { type: 'image/png' });
  return URL.createObjectURL(blob);
}

If at some point you decide that the image is not useful anymore, don't forget to clean it: URL.revokeObjectURL(yourUrl)

like image 43
maxime1992 Avatar answered Oct 24 '22 09:10

maxime1992