//图片预览以及压缩上传
const previewPic = function(event,id) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let ctxW,ctxH,dataURL;
let file = event.target.files[0];
let imgSrc = '';
if(file){
let r = new FileReader();
r.readAsDataURL(file);
r.onload = function(e) {
imgSrc = this.result;
let img = new Image();
img.src = imgSrc;
img.onload = function(){
let width = img.width,height = img.height;
let scale = width / height;
if(width>=height){
ctxW = 226 * scale;
ctxH = 226;
}else{
ctxW = 343;
ctxH = 343/scale;
}
canvas.width = ctxW;
canvas.height = ctxH;
//图片压缩
ctx.drawImage(img,0,0,width,height,0,0,ctxW,ctxH);
imgSrc = canvas.toDataURL("image/jpeg",0.7);
document.getElementById("PIC"+id).setAttribute("src",imgSrc);
dispatch({type:"productEditList/previewPic",payload:{id,imgSrc}})
}
}
}
}
网友评论