如何将img的二进制数据转换为img标签 [英] how to convert the binarydata of img to img tags

查看:730
本文介绍了如何将img的二进制数据转换为img标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有

我得到了图像的二进制数据(使用xhr),让我们将这个二进制数据命名为数据

我想知道如何将数据转换为真正的img标签< br>
首先:

我尝试使用 FileReder 读取 readAsBinaryString ,但它不起作用 reader.onloadend 不会触发



是否有其他方法可以完成此操作?

提前致谢〜$ /
$ b

  $ .ajax({
url:src,
类型:GET,
成功:函数(数据) {
var reader = new FileReader()
reader.onload = function(e){

var data = e.target.result
console.log(data )


reader.readAsDataURL(data)

..

解决方案

Base64编码你的二进制数据。 246801 / how-can-you-encode-to-base64-using-javascript>问题如何在JavaScript中base64二进制数据。



然后将base64字符串直接插入到图像标签中。例如,如果二进制数据是一个JPG图像,你可以这样做(理论上):

  $。ajax({ 
url:src,
类型:GET,
成功:function(binaryData){

// toBase64是一个组合函数,见上面
var base64Data = toBase64(binaryData);

假设img是在这里定义的(不在这个问题的范围之内)
img.src =data:image / jpg ; base64,+ base64Data;
}
});


all
I got the binary data of the image(use xhr),let's name this binary data as data
I wonder how to convert data to a real img tags
At first:
I try using FileReder to readAsBinaryString,but It won't work cause reader.onloadend won't fire

Are there other ways to get this done?
Thanks in advance~

 $.ajax({
                url:src,
                type:"GET",
                success:function(data){  
    var reader=new FileReader()
    reader.onload=function(e){

        var data=e.target.result
        console.log(data)

   } 
  reader.readAsDataURL(data)

...

解决方案

Base64 encode your binary data. See this question on how to base64 binary data in JavaScript.

Then insert the base64 string directly into your image tag. For example, if the binary data is a JPG image, you could do this (in theory):

$.ajax({
  url:src,
  type:"GET",
  success:function(binaryData) {  

    //toBase64 is a made up function, see above
    var base64Data = toBase64(binaryData);

    //assuming img is defined outside of here (not in the scope of this question)
    img.src = "data:image/jpg;base64," + base64Data;
  }
});

这篇关于如何将img的二进制数据转换为img标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆