JS图片上传

作者: zzz1t1 | 来源:发表于2019-11-01 17:10 被阅读0次
    private getBase64(img: File, callback: (img: string) => void): void {
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result!.toString()));
            reader.readAsDataURL(img);
        }
    
    compressImg (file) {
            if (['image/png','image/jpeg','image/jpg'].includes(file.type)) {
                let _this = this;
                this.getBase64(file, (src) => {
                    let img = new Image();
                    img.src = src;
                    img.onload = () => {
                        let originWidth = img.width;
                        let originHeight = img.height;
                        // 目标尺寸
                        let targetWidth = originWidth, targetHeight = originHeight;
                        let maxWidth =  'xxxx';
                        let maxHeight = 'xxx;
                        if (!maxWidth && !maxHeight) {
                            maxWidth = MAX_WIDTH;
                            maxHeight = MAX_HEIGHT;
                        }
                        if (originWidth > maxWidth || originHeight > maxHeight) {
                            if ((maxWidth && maxHeight) && (originWidth / originHeight > maxWidth / maxHeight) || maxWidth) {
                                targetWidth = maxWidth;
                                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                            } else {
                                targetHeight = maxHeight;
                                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                            }
                        }
                        // 新建画布
                        let canvas = document.createElement('canvas');
                        let context = canvas.getContext('2d');
                        canvas.width = targetWidth;
                        canvas.height = targetHeight;
                        // 清除画布
                        context.clearRect(0, 0, targetWidth, targetHeight);
                        // 图片压缩
                        context.drawImage(img, 0, 0, targetWidth, targetHeight);
    
                        canvas.toBlob((blob) => {
                            let formData = new FormData();
                            formData.append('file', blob, file.name);
                            //请求数据
                        })
                    }
                });
            } else {
                console.log('error', '文件格式不正确');
            }
        }
    

    相关文章

      网友评论

        本文标题:JS图片上传

        本文链接:https://www.haomeiwen.com/subject/ejhqbctx.html