前端压缩图片代码片段

09-03
评论
字数统计:2141(字)
前端通过canvas压缩图片,自定义压缩比,解决某些场景上传时不需要过大、过于清晰的图片。
/**
 * 读取文件
 * @param image File 需要压缩的图片
 * @returns Promise<HTMLImageElement>
 */
function readImg(image: File): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const img = document.createElement("img");
    const reader = new FileReader();
    reader.onload = function(e) {
      img.src = e.target?.result as string;
    };
    reader.onerror = function(e) {
      reject(e);
    };
    reader.readAsDataURL(image);
    img.onload = function() {
      resolve(img);
    };
    img.onerror = function(e) {
      reject(e);
    };
  });
}

/**
 * 压缩图片
 * @param image HTMLImageElement 压缩对象
 * @param type 压缩后需要转换的文件类型
 * @param maxWidth 触发压缩的图片最大宽度限制
 * @param maxHeight 触发压缩的图片最大高度限制
 * @returns Promise<Blob | null>
 */
function compressImg(
  image: HTMLImageElement,
  type: string,
  maxWidth: number,
  maxHeight: number
): Promise<Blob | null> {
  return new Promise(resolve => {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d") as CanvasRenderingContext2D;
    const { width: originWidth, height: originHeight } = image;

    // 目标尺寸
    let targetWidth = originWidth;
    let targetHeight = originHeight;

    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > 1) {
        // 过宽处理
        targetWidth = maxWidth;
        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
      } else {
        // 过高处理
        targetHeight = maxHeight;
        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
      }
    }
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    context.clearRect(0, 0, targetWidth, targetHeight);
    // 图片绘制
    context.drawImage(image, 0, 0, targetWidth, targetHeight);
    canvas.toBlob(function(blob) {
      resolve(blob);
    }, type || "image/png");
  });
}

// 调用压缩
export default async function startCompress(file: File): Promise<Blob | null> {
  const img = await readImg(file);
  const blob = await compressImg(img, file.type, 400, 400);
  return blob;
}


本文链接:https://blog.crazylei.com/art/00473c9f
版权声明: 本博客所有文章除特别声明外,均采用CC BY 4.0 CN协议 许可协议。转载请注明出处!

评论

正在加载评论...

相关推荐

暂无推荐
友情链接:互链8收录网
©2022 Crazylei Bolg沪ICP备20001821号