将图像二进制数据转换为img标签

turn image binary data into img tag

本文关键字:img 标签 转换 数据 图像 二进制      更新时间:2023-09-26

当我向路由发送post请求时,我有

/generate/image

我得到类似:var file =

����JFIF��C��C��� ��    
�����+�}Yϭ�F39M>���������>���;��ˋ��uXʽ�w�ڤx'-[2g��k�S���H���m
[�V?[_W����#��v��}6�[��F�F�%����n�...

在客户端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);

但是我得到一个损坏的图像

我能做什么?

编辑:如果我做

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

:

Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

请不要使用base64,浪费带宽和CPU按原样发送图像二进制并使用Ajax正确处理它们。您不应该以字符串的形式获得结果。设置xhr responseType为blob或使用fetch的blob方法。

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

当你有blob时,不要使用文件阅读器将其转换为url。

使用URL.createObjectURL (blob)

在你的后端,你可以这样做:

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 });
});

当我的客户端从套接字接收数据时,我调用函数:

socket.on('image upload', function(data){
                displayImage(data);
            });
var displayImage = function(data){
                var URL = 'data:image/jpg;base64,'+data.buffer;
                document.querySelector('#img-id').src = URL;
            };
然后图像将显示在img标签中。