图像转换为Base64 [英] Image convert to Base64

查看:147
本文介绍了图像转换为Base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < input type =fileid =asd/> 

一旦用户选择了,我想获取 base64 中的图像(在提交表单之前)



如下所示:

  $(输入).on('change',function(){
var data = $(this).val()。base64file(); //它不是一个插件只是一个例子
alert数据);
});

我阅读了关于File API和其他东西,我想要一个简单的跨浏览器解决方案(IE6 / IE7排除明显)



任何帮助谢谢。

解决方案

div class =snippetdata-lang =jsdata-hide =falsedata-console =falsedata-babel =false>

 

 < input id =inptype ='file'>< p id =b64>< / p>< img id =imgheight =150  



PS: / strong> base64编码图像(String)原始图像数据大小的4/3)



检查此答案以多个图像上传



浏览器支持: http:/ /caniuse.com/#search=file%20api

更多信息: https://developer.mozilla.org/en-US/docs/Web/API/FileReader


<input type="file" id="asd"/>

I would like to get the image in base64 once the user chose that (before submitting the form)

Something like :

$(input).on('change',function(){
  var data = $(this).val().base64file(); // it is not a plugin is just an example
  alert(data);
});

I read about File API and other stuffs, I would like a simple and cross-browsers solution (IE6/IE7 excluded obviously)

Any help appreciated thanks.

解决方案

function readFile() {
  
  if (this.files && this.files[0]) {
    
    var FR= new FileReader();
    
    FR.addEventListener("load", function(e) {
      document.getElementById("img").src       = e.target.result;
      document.getElementById("b64").innerHTML = e.target.result;
    }); 
    
    FR.readAsDataURL( this.files[0] );
  }
  
}

document.getElementById("inp").addEventListener("change", readFile);

<input id="inp" type='file'>
<p id="b64"></p>
<img id="img" height="150">

(P.S: A base64 encoded image (String) 4/3 the size of the original image data)

Check this answer for multiple images upload.

Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

这篇关于图像转换为Base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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