compressToTargetSizeJpgOrWebp
将图片压缩到指定的目标文件大小,输出为 JPEG 或 WebP。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.Image | Window['Image'] | Image 构造函数 |
deps.File | Window['File'] | File 构造函数 |
deps.createObjectURL | (blob: File) => string | 创建对象 URL |
deps.createElement | Document['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>参数
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
file | File | 是 | - | 输入(Canvas/Image 可解码的任意图片) |
options.targetSize | number | 否 | 30720 | 目标体积(字节) |
options.outputFormat | 'jpeg' | 'webp' | 否 | 'jpeg' | 输出格式 |
options.strictTarget | boolean | 否 | false | 达不到目标是否抛错 |
deps | CompressToTargetSizeJpgOrWebpDeps | 是 | - | 依赖注入 |
输出说明
| 格式 | 扩展名 | 透明 |
|---|---|---|
jpeg | .jpg | 不支持,铺白底 |
webp | .webp | 传入 createImageBitmap 时可保留;否则白底 |
使用注意
- 输入任意 Canvas 支持的图片;输出只能是 JPEG 或 WebP。
- 小体积 + 透明图优先用
outputFormat: 'webp'并传入createImageBitmap。