对用户上传图片进行压缩

前端图片压缩主要利用 HTML5 中的 Canvas 对象来处理图片。用户上传的图片先在客户端进行压缩,然后再上传到服务器。这种方法可以减少服务器的负担和节省带宽。

步骤如下:
  1. 用户选择图片后,在前端使用 JavaScript 将图片绘制到 Canvas 元素上。
  2. 控制 Canvas 的尺寸,从而改变图片的分辨率或质量。
  3. 将 Canvas 上的内容转换为压缩后的图片格式。
  4. 最后将压缩后的图片上传到服务器。
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .img-box {
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <input type="file" accept="image/*" id="file-input">
    <div class="img-box"></div>
    <script>
        // 获取用户上传的图片文件
        const fileInput = document.getElementById('file-input');
        fileInput.addEventListener('change', function () {
            const file = fileInput.files[0];
            // console.log('file的值', file);
            // 创建一个新的图片对象
            const img = new Image();

            // 添加加载完成的事件处理程序
            img.onload = function () {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                // 控制图片尺寸
                const maxWidth = 800;
                const maxHeight = 600;
                let width = img.width;
                let height = img.height;
                console.log('看看这里会打印东西么', width, height);

                if (width > height) {
                    if (width > maxWidth) {
                        height *= maxWidth / width;
                        width = maxWidth;
                    }
                } else {
                    if (height > maxHeight) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }
                }

                // console.log('看看这里会打印东西么', width, height);

                canvas.width = width;
                canvas.height = height;

                // 在Canvas上绘制压缩后的图片
                ctx.drawImage(img, 0, 0, width, height);

                // 将Canvas上的内容导出为压缩后的Blob对象
                canvas.toBlob((blob) => {
                    // 将Blob对象上传到服务器或其他操作

                    // 这里假设有一个上传图片的接口uploadImageToServer,将Blob对象上传到服务器
                    // const formData = new FormData();
                    // formData.append('image', blob, 'compressed_image.jpg');

                    // fetch('http://example.com/uploadImageToServer', {
                    //     method: 'POST',
                    //     body: formData
                    // })
                    //     .then(response => {
                    //         // 处理服务器响应
                    //     })
                    //     .catch(error => {
                    //         console.error('Error uploading image to server:', error);
                    //     });
                }, 'image/jpeg', 0.3); // 设置压缩质量
            };

            // 读取用户上传的文件并将其作为图片源加载
            const reader = new FileReader();
            // 以 Data URL 的形式读取该文件的内容,然后触发 reader.onload 事件
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                img.src = e.target.result;
                // clientWidth 返回的是元素的可见宽度,包括 padding,但不包括 border、margin 和滚动条。
                // naturalWidth 返回的是图片的原始宽度,对于其他元素返回 0。
                // img.width = img.naturalWidth * 0.3
                // img.height = img.naturalHeight * 0.3

                // 如果需要显示上传的图片,可以将其添加到页面中
                const imgBox = document.getElementsByClassName('img-box')[0]
                imgBox.appendChild(img);
            };
        });

    </script>
</body>

</html>

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值