Skip to content Skip to sidebar Skip to footer

Turn Image Binary Data Into Img Tag

When i do a post request to a route i have /generate/image i get something like: var file = ����JFIF��C��C��� �� �����+�}Yϭ�F39M>

Solution 1:

Please don't use base64 and wast bandwidth + CPU Send the image binary as is and handle them correctly with Ajax. You should not get the result as a string. set xhr responseType to blob or use fetch's blob method.

fetch("/generate/image").then(res => res.blob())

When you have the blob don't use the file reader to turn it to a url.

Use URL.createObjectURL(blob)

Solution 2:

At your backend you can do following:

var fs = require('fs');
fs.readFile(path to image from you file, 'base64', function(err, buf){
      /* Here you can send your base64 image data to client. Your base64 data is in buf. 
      I am using socket. You can just send. Read more about readFile function*/
      socket.emit('image upload', { image: true, buffer: buf });
});

As my client receives data from socket, I call a function:

socket.on('image upload', function(data){
                displayImage(data);
            });

var displayImage = function(data){
                varURL = 'data:image/jpg;base64,'+data.buffer;
                document.querySelector('#img-id').src = URL;
            };

The image will then be showed in img tag. Hope this works for you.

Post a Comment for "Turn Image Binary Data Into Img Tag"