<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file" id="upload"></input>
    <script>
        const ACCEPT = ['image/jpg', 'image/png', 'image/jpeg'];
        const MAXSIZE = 3 * 1024 * 1024;
        const MAXSIZE_STR = '3MB';

        // 读取图片方法
        function converImageToBase64(file, callback) {
            let reader = new FileReader();
            reader.addEventListener('load', function(e) {
                const base64Image = e.target.result; // 读取图片
                callback && callback(base64Image)
                reader = null; // 回收
            })
            reader.readAsDataURL(file);
        }
        // 压缩方法1
        function compress(base64Image, callback) {
            console.log(base64Image);
            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;
                    console.log('压缩比例', ratio);
                    maxH = image.naturalHeight / ratio; // 获得高度压缩值
                } // 经过处理后,实际图片的尺寸为1024 * 640 ;
                if (maxH < image.naturalHeight) {
                    needCompress = true;
                    ratio = image.naturalHeight / maxH;
                    maxW = image.naturalWidth / ratio;
                }
                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'; // visible可显示
                document.body.appendChild(canvas);

                const ctx = canvas.getContext('2d');
                ctx.clearRect(0, 0, maxW, maxH);
                ctx.drawImage(image, 0, 0, maxW, maxH);
                // 质量压缩-start
                const compressImage = canvas.toDataURL('image/jpeg', 0.8); // 参数二:压缩比例0-1
                callback && callback(compressImage);
                //挂载到页面-一下;对比
                const _image = new Image();
                _image.src = compressImage;
                document.body.append(_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;
            console.log(e.target.files);
            if (!file) {
                return;
            }
            const {
                type: fileType,
                size: fileSize
            } = file;
            // if(ACCEPT.indexOf(fileType) < 0) {
            if (!ACCEPT.includes(fileType)) {
                // alert('不支持[' + fileType + ']文件类型!');
                alert(`不支持[${fileType}]文件类型!`);
                upload.value = '';
                return;
            }
            if (fileSize > MAXSIZE) {
                alert(`文件超出${MAXSIZE_STR}`);
                upload.value = '';
                return;
            }
            // 调用方法--开始压缩1
            converImageToBase64(file, (base64Image) => compress(base64Image, uploadToServer))

        })
    </script>
</body>

</html>