Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>���������>���;��ˋ��uXʽ�w�ڤx\-[2g��k�S���H���m
[�V?[_W����#��v��}6�[��F�F�%����n�...

in the client i do:

var blob = new Blob([file], {type: 'image/png'});
var reader = new FileReader();

reader.onload = function (e) {
   $('#result').attr('src', e.target.result);
};

reader.readAsDataURL(blob);

but i get a corrupt image

what can i do?

EDIT: if i do

img.src = 'data:image/png;base64,' + btoa(file);

i get:

Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
like image 885
Abdul Hamid Avatar asked Jun 24 '26 05:06

Abdul Hamid


1 Answers

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)

like image 81
Endless Avatar answered Jun 25 '26 18:06

Endless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!