封装了几个方法,主要是传入input对象,将对象选中的文件转程base64形式。可以用于图片上传,图片选中后马上显示等功能
1.读取input对象图片,并调用2执行压缩
/**
* input对象内的图片转Base64
* @param inputOb input对象
* @param outputFun 转换后执行的函数,有一个base64的形参
* */
function inputImgToBase64(inputOb,outputFun) {
var file=inputOb.files[0]
if(!/image\/\w+/.test(file.type))//判断获取的是否为图片文件
{
alert("请确保文件为图像文件");
return false;
}
var reader=new FileReader();
reader.readAsDataURL(file);
reader.onload=function(e)
{
var image = new Image();
//文件类型
image.imgType = file.type;
//保存后缀
var fileNameList = file.name.split('.');
var fileType = fileNameList[fileNameList.length-1];
$('#photoType').attr('value',fileType);
image.src = e.target.result;
image.onload = function() {
var expectWidth = 480;
var expectHeight = 640;
var base64 = compress(this,expectWidth,expectHeight,1);
outputFun(base64);
}
}
}
2.图片转base64
/**
* 图片转base64
* @param img img对象
* @param width
* @param height
* @param ratio 比例
* @returns base64Img
*/
function compress(img, width, height, ratio) {
var canvas, ctx, img64;
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
img64 = canvas.toDataURL(img.imgType, ratio);
return img64;
}
使用方式
//input对象,函数
inputImgToBase64($('#inputPhoto')[0],function (base64) {//base64为转换后图像的base64编码
$('#output')[0].src=base64
});