昨天用html5写一个手机上传图片问题,因为用户不可能自己剪辑图片,所以要在客户端生成缩图,不然用户没传两张把人家流量耗光了。
代码如下,
oImage.src="data:application/octet-stream;"+e.target.result.substr(e.target.result.indexOf("base64,"));是重点,因为发现android系统直接选择相册的话,老是显示不了预览图,这样不能把图片放到canvas里面,所以直接把base64前面的东西删除,然后加上mime
希望对有同样问题的同学有帮助,目前我使用
canvas.toDataURL("image/png");因为有些浏览器不支持image/jpeg格式,但是png格式文件大,所以只生成640*640
function fileSelected() { // hide different warnings // get selected file element var oFile = document.getElementById(‘image_file‘).files[0]; // filter for image files var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i; // little test for filesize showerror sResultFileSize=oFile.size; if (sResultFileSize > iMaxFilesize) { return; } // get preview element var oImage = document.getElementById(‘preview‘); // prepare HTML5 FileReader document.getElementById(‘showerror‘).innerHTML=‘正在读取文件。。。(要十多秒)请稍候‘; var oReader = new FileReader(); oReader.onload = function(e){ oImage.src = e.target.result; oImage.src="data:application/octet-stream;"+e.target.result.substr(e.target.result.indexOf("base64,")); oImage.onload = function () { // binding onload event //nwidth=oImage.naturalWidth;//原始图片的宽和高 //nheight=oImage.naturalHeight; //sizemyimg(640,640);//自动缩放到640*640 //drawimg(oImage);//把图片传到canvas里面 // we are going to display some custom image information here sResultFileSize = bytesToSize(oFile.size); document.getElementById(‘showerror‘).innerHTML=‘读取完成,请点上传按扭,有多张图片请继续上传‘; fileup=false; }; oImage.onerror=function(){ document.getElementById(‘showerror‘).innerHTML=‘没有缩略图,请拍照或点上传按扭,有多张图片请继续上传‘; fileup=true; } }; oReader.readAsDataURL(oFile); } function drawimg(oimg){ canvas = document.getElementById("myCanvas"); canvas.width = newwidth; canvas.height = newheight; ctx = canvas.getContext(‘2d‘); ctx.drawImage(oimg, 0, 0, nwidth, nheight,0, 0, newwidth, newheight); pic=canvas.toDataURL("image/png"); pic=pic.substr(22); }