Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 图片压缩

作者:余烬已熄   发布日期:2025-05-31   浏览:30

// 使用 HTML5 Canvas 和 JavaScript 实现图片压缩

function compressImage(file, maxWidth, maxHeight, quality) {
    // 创建一个读取文件的 FileReader 对象
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(event) {
            const img = new Image();
            img.src = event.target.result;
            img.onload = function() {
                let elem = document.createElement('canvas');
                let ctx = elem.getContext('2d');

                // 获取原始图片的宽高
                let width = img.width;
                let height = img.height;

                // 计算压缩后的宽高
                if (width > height) {
                    if (width > maxWidth) {
                        height = Math.round(height *= maxWidth / width);
                        width = maxWidth;
                    }
                } else {
                    if (height > maxHeight) {
                        width = Math.round(width *= maxHeight / height);
                        height = maxHeight;
                    }
                }

                // 设置 canvas 的尺寸为新的宽高
                elem.width = width;
                elem.height = height;

                // 将图片绘制到 canvas 上
                ctx.drawImage(img, 0, 0, width, height);

                // 将 canvas 转换为带有指定质量的 base64 图片
                elem.toBlob(function(blob) {
                    resolve(blob);
                }, file.type, quality);
            };
            img.onerror = function(error) {
                reject(error);
            };
        };
        reader.onerror = function(error) {
            reject(error);
        };
    });
}

// 示例用法:
// 假设你有一个 <input type="file" id="imageInput"> 元素用于选择图片
document.getElementById('imageInput').addEventListener('change', async function(event) {
    const file = event.target.files[0];
    if (file) {
        try {
            const compressedFile = await compressImage(file, 800, 600, 0.7); // 宽度最大 800px,高度最大 600px,质量 70%
            console.log(compressedFile); // 输出压缩后的文件对象
        } catch (error) {
            console.error('图片压缩失败:', error);
        }
    }
});

上一篇:js base64.encode

下一篇:js 取余数

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js jsonp

js 获取当前页面url

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站