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

Angular4图片上传:不重构模块前提下修改函数实现图片压缩

解决方案:在现有save函数中嵌入图片压缩逻辑

完全理解你不想改动现有架构的需求,我们可以直接在你现有的save函数里添加图片压缩逻辑,不需要重构模块。核心思路是利用浏览器的canvas API对图片进行压缩,生成体积更小的文件后再传给后端。

以下是修改后的完整save函数,我会在代码后面解释关键改动:

save(event: any, type, image_type) { 
  this.uploadImageFlag = true; 
  const fileList: FileList = event.target.files; 
  if (fileList.length > 0) { 
    const file: File = fileList[0];
    // 先判断是否是图片类型,避免非图片文件走压缩流程
    if (!file.type.startsWith('image/')) {
      this.files.set('files', file, file.name);
      const reader = new FileReader(); 
      reader.onload = (event: any) => { 
        this.url2 = event.target.result; 
        this.upload = true; 
      } 
      reader.readAsDataURL(file);
      return;
    }

    const reader = new FileReader(); 
    reader.onload = (event: any) => { 
      // 创建Image对象加载原图
      const img = new Image();
      img.src = event.target.result;
      img.onload = () => {
        // 压缩配置:可根据需求调整
        const maxWidth = 1920; // 最大宽度,超过就按比例缩放
        const maxHeight = 1080; // 最大高度
        const quality = 0.7; // 压缩质量,0-1之间,值越小体积越小

        // 计算压缩后的宽高,保持比例避免变形
        let width = img.width;
        let height = img.height;
        if (width > maxWidth) {
          height = (height * maxWidth) / width;
          width = maxWidth;
        }
        if (height > maxHeight) {
          width = (width * maxHeight) / height;
          height = maxHeight;
        }

        // 创建canvas绘制压缩后的图片
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        ctx?.drawImage(img, 0, 0, width, height);

        // 将canvas转为Blob,再转为File对象
        canvas.toBlob((blob) => {
          if (blob) {
            // 生成新的File对象,保留原文件名和类型
            const compressedFile = new File([blob], file.name, { type: file.type });
            // 更新files对象,替换为压缩后的文件
            this.files.set('files', compressedFile, compressedFile.name);
            // 将压缩后的图片转为dataURL赋值给url2
            this.url2 = canvas.toDataURL(file.type, quality);
            this.upload = true;
          }
        }, file.type, quality);
      };
    } 
    reader.readAsDataURL(file); 
  } 
}

关键改动说明:

  1. 类型校验:先检查文件是否为图片类型,非图片文件直接走原有逻辑,避免不必要的处理和错误。
  2. 无损比例压缩:通过计算原图宽高与设定的最大宽高比例,保证压缩后的图片不会变形。
  3. 无缝替换原文件:将压缩后的Blob转为File对象,直接替换掉原来存入this.files的文件,确保后续传给后端的是压缩后的小体积文件。
  4. 灵活配置:你可以根据业务需求调整maxWidth、maxHeight和quality参数,在图片质量和传输速度之间找到平衡点。

这个改动完全嵌入到你现有的函数流程中,没有修改任何外部调用或模块结构,只在原有逻辑中加入了压缩步骤,完美契合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:42:35