js 图片转换为base64 (2)

<input type="file" id="testUpload">
<img src="" id="img" alt="">
<script>
// 前端只需要给input file绑定这个change事件即可(下面两个方法不需要修改)获取到图片
$('#testUpload').change(function(event){
var imageUrl = getObjectURL($(this)[0].files[0]);
//imageUrl = staticpath+"/images/businessLicensePath_1511499859533.png";
convertImgToBase64(imageUrl, function(base64Img){
$("#img").attr("src",base64Img);
console.log(base64Img);
//base64Img为转好的base64,放在img src直接前台展示(<img src="data:image/jpg;base64,/9j/4QMZRXh...." />)
//alert(base64Img);
$("#base").attr("src",base64Img);
//base64转图片不需要base64的前缀data:image/jpg;base64
//alert(base64Img.split(",")[1]);
$("#uploadFile").val(base64Img.split(",")[1]);
});
event.preventDefault();
});
 
//生成图片的base64编码
function convertImgToBase64(url, callback, outputFormat){
//html5 的convas画布
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
var width = img.width;
var height = img.height;
// 按比例压缩4倍
//var rate = (width<height ? width/height : height/width)/4;
//原比例生成画布图片
var rate = 1;
canvas.width = width*rate;
canvas.height = height*rate;
ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);
// canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
 
//createobjecturl()静态方法创建一个包含了DOMString代表参数对象的URL。该url的声明周期是在该窗口中.也就是说创建浏览器创建了一个代表该图片的Url.
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined){
// basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined){
// mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined){
//web_kit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
</script>
上一篇:在Sublime Text 3中配置Python3的开发环境/Build System


下一篇:Oracle 11g 新特性 – HM(Hang Manager)简介