首页 > 代码库 > 前端预览图片和H5canvas压缩图片上传

前端预览图片和H5canvas压缩图片上传

思路是将图片抽样显示在canvas上,然后用通过canvas.toDataURL方法得到base64字符串来实现压缩。

1.base64转二进制文件

/** * dataURL to blob, ref to https://gist.github.com/fupslot/5015897 * @param dataURI * @returns {Blob} */function dataURItoBlob(dataURI) {    var byteString = atob(dataURI.split(‘,‘)[1]);    var mimeString = dataURI.split(‘,‘)[0].split(‘:‘)[1].split(‘;‘)[0];    var ab = new ArrayBuffer(byteString.length);    var ia = new Uint8Array(ab);    for (var i = 0; i < byteString.length; i++) {        ia[i] = byteString.charCodeAt(i);    }    return new Blob([ab], {type: mimeString});}

2.压缩 参数(图片对象,品质,输出格式) 返回压缩后图片对象

function compress(source_img_obj, quality, output_format){        var mime_type = "image/jpeg";        if(output_format!=undefined && output_format=="png"){            mime_type = "image/png";        }        var cvs = document.createElement(‘canvas‘);                 //naturalWidth真实图片的宽度                 cvs.width = source_img_obj.naturalWidth;                 cvs.height = source_img_obj.naturalHeight;                 var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);                 var newImageData = http://www.mamicode.com/cvs.toDataURL(mime_type, quality/100);"color: #0000ff;">var result_image_obj = new Image();                 result_image_obj.src = newImageData;                 return result_image_obj;}

3.主要流程

  • 获得和读取图片对象
  • 创建canvas,尺寸设置压缩后的图片尺寸  
  • 调用drawImage方法,把图片绘制到canvas
  • 调用canvastoDataURL,取出 base64 格式的数据
  • 调用dataURItoBlob方法转为二进制文件,再构造FormData填充二进制文件数据,通过ajax的方式进行提交
var file = e.target.files[0];var reader = new FileReader(); //读取文件对象 reader.onload = (function(theFile) {var img = document.getElementById("img-fileUpload_compress") //onload和onloadendvar quality =  10; //图片品质1-100img.src = event.target.result //reader.resultwindow.setTimeout(function(){var imgObj = compress(img,quality) //压缩后的图片var src =http://www.mamicode.com/ imgObj.src; //图片的base64格式可以直接当成img的src属性值img.src = src;var file = dataURItoBlob(src);//转二进制file.filename = Math.round(Math.random()*100000000000000,0)+".jpg";// 调上传接口},1)});reader.readAsDataURL(file);

 

前端预览图片和H5canvas压缩图片上传