图片预览以及压缩上传

2019-03-16  本文已影响0人  JaniceD
//图片预览以及压缩上传
    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}})
                }
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读