canvas实现图片压缩

canvas实现图片压缩


  1. 使用input标签用于上传图片

  2. 监听文件上传,进行图片类型检查图片容量检查

  3. 压缩图片

    3.1 使用reader获取图片base64

    3.2 计算图片的压缩尺寸

    3.3 将图片绘制到canvas上面,对canvas进行压缩处理,获得新的baseURL

4.上传图片


<input type="file" id="upload">
    <script>
        //可上传的图片格式
        const ACCEPT = [ 'image/jpg','image/png','image/jpeg' ];
        // 可上传的最大图片容量
        const MAXIZE = 3*1024*1024;
        const MAXIZE_STR = '3MB';
        // 方法:图片转为base64
        function convertImageToBase64(file,callback){
            let reader = new FileReader();
            reader.addEventListener('load',function(e){
                const base64Image = e.target.result;
                callback && callback(base64Image);
                reader = null;
            })
            // 读取文件内容
            reader.readAsDataURL(file);
        }
        // 方法:压缩图片
        function compress(base64Image,callback){
            let maxW = 1024;
            let maxH = 1024;
            const image = new Image();
            image.addEventListener('load',function(e){
                let ratio; //图片的压缩比
                let needCompress = false;//是否需要压缩
                // 比较图片的实际宽高是否超出
                if(maxW < image.naturalWidth){
                    needCompress = true;
                    ratio = image.naturalWidth / maxW;
                    //图片高度也需要等比压缩
                    maxH = image.naturalHeight / ratio
                } //经过处理后,实际图片的尺寸为 1024 * 576
                if(maxH < image.naturalHeight){
                    needCompress = true;
                    ratio = image.naturalHeight / maxH;
                    maxW = image.naturalWidth / ratio;
                } //经过处理后,实际图片的尺寸为 1024 * 576
                if(!needCompress){
                    maxW = image.naturalWidth;
                    maxH = image.naturalHeight;
                } //如果不需要压缩,需要获取图片的实际尺寸
                const canvas = document.createElement('canvas');
                canvas.setAttribute('id','__compress__');
                canvas.width = maxW;
                canvas.height = maxH;
                canvas.style.visibility = 'hidden';
                document.body.appendChild(canvas);

                const ctx = canvas.getContext('2d');
                ctx.clearRect(0,0,maxW,maxH);
                ctx.drawImage(image,0,0,maxW,maxH);
                const compressImage = canvas.toDataURL('image/jpeg',0.85);
                callback && callback(compressImage)
                const _image = new Image();
                _image.src = compressImage;
                document.body.appendChild(_image);
                canvas.remove()
                console.log('压缩比:'+image.src.length / _image.src.length);
            })
            image.src = base64Image;
            document.body.appendChild(image)
        }
        // 方法:上传图片
        function uploadToServer(compressImage){
            console.log('upload to server...',compressImage);
        }
        // 监听图片上传
        const upload = document.getElementById('upload');
        upload.addEventListener('change',function(e){
            const [file] = e.target.files;
            if(!file){
                return;
            }
            const { type:fileType,size:fileSize } = file;
            // 图片类型检查
            if(!ACCEPT.includes(fileType)){
                alert('不支持['+fileType+']文件类型!');
                upload.value = '';
                return;
            }
            // 图片容量检查
            if(fileSize>MAXIZE){
                alert(`文件超出${MAXIZE_STR}`);
                upload.value = '';
                return
            }
            // 压缩图片
            convertImageToBase64(file,(base64Image)=>compress(base64Image,uploadToServer));
        })
    </script>

参考:

https://blog.csdn.net/m0_49914065/article/details/118190717

posted @ 2022-07-10 15:59  小风车吱呀转  阅读(1171)  评论(0编辑  收藏  举报