function canvasDataURL(path, obj, callback) { var img = new Image(); img.src = path; img.onload = function () { var that = this; // 默认按比例压缩 var w = that.width, h = that.height, scale = w / h; w = obj.width || w; h = obj.height || w / scale; var quality = 0.7; // 默认图片质量为0.7 //生成canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); // 创建属性节点 var anw = document.createAttribute("width"); anw.nodeValue = w; var anh = document.createAttribute("height"); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); ctx.drawImage(that, 0, 0, w, h); // 图像质量 if (obj.quality && obj.quality <= 1 && obj.quality > 0) { quality = obj.quality; } // quality值越小,所绘制出的图像越模糊 var base64 = canvas.toDataURL("image/jpeg", quality); // 回调函数返回base64的值 callback(base64); }; } /** * 将以base64的图片url数据转换为Blob * @param urlData * 用url方式表示的base64图片数据 */ function convertBase64UrlToBlob(urlData, fileName) { var arr = urlData.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([new Blob([u8arr])], fileName, { type: mime }); }
在项目中引用
let files= $(''input[file]'')[0].files[0]; photoCompress( files, { quality: 0.2 }, function(base64) { var bl = convertBase64UrlToBlob(base64,fileName); formData1.append("file", bl); //上传代码 } );