下述插件jquery.upLoadImg.js旨在不借助任何插件的前提下,优化移动端用户在web页面上传图片卡顿或消耗流量过大问题。大概思路,先用FileReader对象从本地获取上传图像,转为base64图片流,再由此生成Image对象,用canvas按比例压缩绘制,并返回压缩后的图片流,上送给后台服务器
HTML:(html是次要的,自由发挥吧)
<img id="showImg" src="默认背景图片" alt="" />
<input type="file" id="file" οnchange="readAsDataURL('file','showImg')" />
jquery.upLoadImg.js:
/**
* upLoadImg (http://blog.csdn.net/u598975767/article/details/75500890)
* 基于jquery+html5 上传及压缩图片
* @version v0.1
* @author benboerba
*/
;(function($){
var imgFiles=function(el,opt){
this.element=el;
this.file=el[0].files[0];
this.default={
"showImage":"",//需要展示的img标签Id
"width":375,//目标图片宽度,为保证图片不失真或变形,高度会等比例变化
"quality":0.8,//图片质量,取值0-1之间
"callBack":function(){}
};
this.options=$.extend({},this.default,opt);
};
/**
* 压缩图片 创建一个image对象,给canvas绘制使用
* @params image:图片对象
* @return 返回一个上送给后台的图片流
*/
imgFiles.prototype.compress=function(image){
var cvs = document.createElement('canvas');
//根据设备宽度高,设定缩放后的宽度,计算出缩放比例,建议以宽度为准
var scale = this.options.width / image.width;
//计算等比缩小后图片宽高
cvs.width = image.width*scale;
cvs.height = image.height*scale;
var ctx = cvs.getContext('2d');
ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
var newImageData = cvs.toDataURL(this.file.type,this.options.quality);
var sendData = newImageData.replace("data:"+this.file.type+";base64,",'');
return sendData;
};
/**
* 上传图片
*/
imgFiles.prototype.getImages=function(){
var $that=this;
var files = $that.file;
//检验是否为图像文件
if(!/image\/\w+/.test(files.type)){
alert("请选择图片");
$that.element.val("");
return false;
}
var reader = new FileReader();
//将文件以Data URL形式读入页面
reader.readAsDataURL(files);
reader.οnlοad=function(e){
var result = this.result;
if($("#"+$that.options.showImage)){
$("#"+$that.options.showImage).attr({"src": result});
}
var image = new Image();
image.src = result;
image.onload = function(){
$that.options.callBack($that.compress(image));
};
};
};
$.fn.upLoadImg=function(options){
var img= new imgFiles(this, options);
img.getImages();
};
})(jQuery);
调用js:
<script type="text/javascript">
var readAsDataURL=function(file,showId){
$("#"+file).upLoadImg({
"showImage":showId,
"width":375,
"callBack":function(imgStream){
var params = {"***" : imgStream};
$.ajax({
url: "test.html",
data:JSON.stringify(params),
success: function(data){
alert("图片上传成功啦");
}
});
}
});
};
</script>
上述代码基于jquery,别忘了导入jquery框架!第一次封装插件,有不到的地方,望大牛指出纠正!谢谢!