You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript图片压缩函数中添加修改图片尺寸功能?

如何在图片压缩函数中添加修改图片长宽的功能?

你可以通过以下几步修改你的compressImage函数,实现自定义图片长宽的需求,同时还能灵活控制是否保持图片比例避免拉伸:

1. 扩展函数配置参数

给函数的第二个参数添加targetWidth、targetHeight选项,同时增加默认开启的keepAspectRatio参数,用来控制是否保持图片原有比例,提升函数灵活性。

2. 计算目标画布尺寸

根据原图尺寸和你指定的目标尺寸,计算最终的画布宽高:如果开启比例保持,就取最小缩放比例计算,避免图片变形;如果关闭比例保持,则直接使用你指定的宽高。

3. 修改画布尺寸并缩放绘制图片

把canvas的宽高设置为计算后的目标尺寸,再用drawImage的多参数版本实现缩放绘制。

修改后的完整代码如下:

const compressImage = async (file, { 
  quality = 1, 
  type = file.type,
  targetWidth, 
  targetHeight,
  keepAspectRatio = true
}) => {
    // 获取图片数据
    const imageBitmap = await createImageBitmap(file);
    let finalWidth = imageBitmap.width;
    let finalHeight = imageBitmap.height;

    // 如果指定了目标宽高,计算最终尺寸
    if (targetWidth || targetHeight) {
        if (keepAspectRatio) {
            // 计算缩放比例,取最小的那个避免拉伸
            const widthRatio = targetWidth ? targetWidth / imageBitmap.width : Infinity;
            const heightRatio = targetHeight ? targetHeight / imageBitmap.height : Infinity;
            const scaleRatio = Math.min(widthRatio, heightRatio);
            finalWidth = Math.round(imageBitmap.width * scaleRatio);
            finalHeight = Math.round(imageBitmap.height * scaleRatio);
        } else {
            // 不保持比例,直接用指定的宽高(没指定的维度用原图尺寸)
            finalWidth = targetWidth || imageBitmap.width;
            finalHeight = targetHeight || imageBitmap.height;
        }
    }

    // 创建画布并绘制缩放后的图片
    const canvas = document.createElement('canvas');
    canvas.width = finalWidth;
    canvas.height = finalHeight;
    const ctx = canvas.getContext('2d');
    // 使用drawImage的缩放参数:图像源, 画布X坐标, 画布Y坐标, 目标宽度, 目标高度
    ctx.drawImage(imageBitmap, 0, 0, finalWidth, finalHeight);

    // 转换为Blob
    const blob = await new Promise((resolve) =>
        canvas.toBlob(resolve, type, quality)
    );

    // 转换为File对象返回
    return new File([blob], file.name, {
        type: blob.type,
    });
};

// 文件输入框监听逻辑
const input = document.querySelector('.my-image-field');
input.addEventListener('change', async (e) => {
    const { files } = e.target;
    if (!files.length) return;

    const dataTransfer = new DataTransfer();

    for (const file of files) {
        if (!file.type.startsWith('image')) {
            dataTransfer.items.add(file);
            continue;
        }

        // 调用时可按需指定目标尺寸,比如缩放到宽400px并保持比例
        const compressedFile = await compressImage(file, {
            quality: 0.3,
            type: 'image/jpeg',
            targetWidth: 400, // 自定义目标宽度
            // targetHeight: 300, // 也可单独指定高度,或同时指定宽高
        });

        dataTransfer.items.add(compressedFile);
    }

    e.target.files = dataTransfer.files;
});

关键说明:

  • 若只指定targetWidth或targetHeight其中一个,开启keepAspectRatio时会自动计算另一个维度,确保图片比例不变
  • 关闭keepAspectRatio后,会强制使用你指定的宽高,图片可能出现拉伸变形,按需选择即可
  • drawImage的多参数写法是实现图片缩放的核心,通过最后两个参数控制绘制到画布上的尺寸

内容的提问来源于stack exchange,提问作者Aliparsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:33:18