图片转Base64 [英] Image convert to Base64

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

问题描述

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

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

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

类似:

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

我阅读了有关 File API 和其他内容的信息,我想要一个简单的跨浏览器解决方案(IE6/IE7 显然不包括在内)

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

任何帮助表示感谢.

推荐答案

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:base64 编码的图像(字符串)是原始图像数据大小的 4/3)

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

检查这个答案多张图片上传.

浏览器支持:http://caniuse.com/#search=file%20api
更多信息:https://developer.mozilla.org/en-US/docs/Web/API/FileReader

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

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