Skip to content

compressToTargetSizeJpgOrWebp

将图片压缩到指定的目标文件大小,输出为 JPEG 或 WebP

前置依赖

依赖参数

参数名类型说明
deps.ImageWindow['Image']Image 构造函数
deps.FileWindow['File']File 构造函数
deps.createObjectURL(blob: File) => string创建对象 URL
deps.createElementDocument['createElement']创建 canvas 元素
deps.createImageBitmap可选输出 WebP 且需保留透明时建议传入

环境要求

  • 浏览器环境: Canvas、Image、URL API

函数签名

typescript
type CompressOutputFormat = 'jpeg' | 'webp'

function compressToTargetSizeJpgOrWebp(
  file: File,
  options?: {
    targetSize?: number
    maxIterations?: number
    outputFormat?: CompressOutputFormat  // 默认 'jpeg'
    strictTarget?: boolean
  },
  deps: CompressToTargetSizeJpgOrWebpDeps
): Promise<File>

参数

参数名类型必填默认值说明
fileFile-输入(Canvas/Image 可解码的任意图片)
options.targetSizenumber30720目标体积(字节)
options.outputFormat'jpeg' | 'webp''jpeg'输出格式
options.strictTargetbooleanfalse达不到目标是否抛错
depsCompressToTargetSizeJpgOrWebpDeps-依赖注入

输出说明

格式扩展名透明
jpeg.jpg不支持,铺白底
webp.webp传入 createImageBitmap 时可保留;否则白底

使用注意

  • 输入任意 Canvas 支持的图片;输出只能是 JPEG 或 WebP
  • 小体积 + 透明图优先用 outputFormat: 'webp' 并传入 createImageBitmap