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

js 压缩图片

作者:飒舛流寒   发布日期:2026-07-24   浏览:47

// 使用 HTML5 Canvas 和 JavaScript 压缩图片的示例代码

function compressImage(file, maxWidth, maxHeight, quality) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(event) {
            const img = new Image();
            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 *= maxWidth / width;
                        width = maxWidth;
                    }
                } else {
                    if (height > maxHeight) {
                        width *= maxHeight / height;
                        height = maxHeight;
                    }
                }

                elem.width = width;
                elem.height = height;

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

                // 将 canvas 转换为压缩后的图片
                elem.toBlob(function(blob) {
                    resolve(blob);
                }, 'image/jpeg', quality);
            };
            img.src = event.target.result;
        };
        reader.onerror = function(error) {
            reject(error);
        };
        reader.readAsDataURL(file);
    });
}

// 示例用法
const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', async function(event) {
    const file = event.target.files[0];
    try {
        const compressedFile = await compressImage(file, 800, 600, 0.7); // 最大宽度800px,最大高度600px,质量70%
        console.log(compressedFile); // 这是压缩后的文件对象
    } catch (error) {
        console.error('Error compressing image:', error);
    }
});

解释说明:

  1. compressImage 函数:

    • 接受四个参数:file(要压缩的图片文件)、maxWidth(最大宽度)、maxHeight(最大高度)和 quality(压缩质量,范围从 0 到 1)。
    • 使用 FileReader 读取图片文件,并将其加载到 Image 对象中。
    • 计算新的宽度和高度以保持原始比例,并确保不超过指定的最大宽度和高度。
    • 使用 Canvas 绘制调整大小后的图像,并通过 toBlob 方法将图像转换为压缩后的 Blob 文件。
  2. 示例用法:

    • 监听文件输入控件的 change 事件,当用户选择图片时,调用 compressImage 函数进行压缩。
    • 压缩后的文件对象可以通过 console.log 或其他方式处理。

上一篇:js 压缩工具

下一篇:js change事件 获取新值和旧值

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站