图像转换为Base64 [英] Image convert to Base64
问题描述
<输入类型=文件ID =ASD/>
我想获得的图像中的的base64 一旦用户选用了(提交表单前)
Somenthing这样的:
$(输入)。在('变',函数(){
VAR数据= $(本).VAL()base64file()。 //它不是一个插件是只是一个例子
警报(数据);
});
我红有关文件API和其他的东西,我想一个简单的和跨浏览器的解决方案(IE6 / IE7显然除外)
任何帮助appriciated感谢。
功能EL(ID){返回的document.getElementById(id)的; } //获取EL由ID辅助函数\r
\r
功能ReadFile的(){\r
如果(this.files&放大器;&放大器; this.files [0]){\r
VAR FR =新的FileReader();\r
FR.onload =功能(E){\r
EL(img目录)SRC = e.target.result。\r
EL(B64)的innerHTML = e.target.result。\r
};\r
FR.readAsDataURL(this.files [0]);\r
}\r
}\r
\r
EL(INP)的addEventListener(变,READFILE,FALSE);
\r
<输入ID =INP类型='文件'>\r
&下,P ID =B64>&下; / P>\r
< IMG ID =IMG>
\r
<子>( P.S:一个base64 EN codeD映像(字符串)比原始图像数据的4/3个头大)
<一个href=\"http://stackoverflow.com/questions/12570834/how-to-$p$pview-image-get-file-size-image-height-and-width-before-upload\">Check这个答案对于多张图片上传 。
浏览器支持: http://caniuse.com/#search=file%20api 结果
更多资讯:<一href=\"https://developer.mozilla.org/en-US/docs/Web/API/FileReader\">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 choosed that (before submitting the form)
Somenthing like :
$(input).on('change',function(){
var data = $(this).val().base64file(); // it is not a plugin is just an example
alert(data);
});
i red about File API and other stuffs, i would like a simple and cross-browsers solution (IE6/IE7 excluded obviously)
Any help appriciated thanks.
function EL(id) { return document.getElementById(id); } // Get el by ID helper function
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.onload = function(e) {
EL("img").src = e.target.result;
EL("b64").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
EL("inp").addEventListener("change", readFile, false);
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img">
(P.S: A base64 encoded image (String) is 4/3 bigger in size than 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屋!