图像压缩处理器
更新时间:2026-04-23
简介
图像压缩处理器
功能描述
-
输入格式:
- 本地地址(image_url: file://path)
- BOS路径 ("bos://{bucket}/{path}")
- Base64 编码(image_base64)
- 二进制流(image_binary)
-
压缩与缩放:
- 质量压缩(quality 参数)
- 尺寸缩放(target_size 或保持原尺寸)
- 多种插值算法:nearest / bilinear / bicubic / lanczos
-
输出模式:
- 返回压缩后图片的 Base64 字符串
- 可选将图片保存到本地目录
-
格式适配:
- JPEG:质量压缩 + RGBA 转 RGB
- PNG:无损压缩(compress_level) + 保留透明通道
- WebP:质量/无损压缩 + 保留透明通道
算子参数
输入
| 输入 | 含义 |
|---|---|
| image | 包含输入图像的数组,支持URL/base64/二进制格式 |
| image_name | 可选参数,包含图像标识名的数组,用于生成输出文件名 |
输出
| 输出 | 含义 |
|---|---|
| base64 | 压缩后图像的base64编码 |
| image_path | 本地存储路径(当配置输出目录时有效) |
参数
| 参数 | 类型 | 含义 | 默认值 |
|---|---|---|---|
| image_suffix | str | 保存到本地 时使用的文件后缀,需为支持的格式。可选值: [".jpg", ".jpeg", ".png", ".webp"] | .jpg |
| output_dir | str | 将压缩后的图像保存到的输出路径,为空则不保存到输出 | "" |
| image_src_type | str | 输入图像的格式类型。可选值: ["image_url", "image_base64", "image_binary"] | image_url |
| target_size | list | 压缩后图像的尺寸。格式为 [width, height];None 表示保持原尺寸。 | None |
| quality | int | 压缩质量参数(适配不同格式):JPEG/WebP:1-100(数值越高质量越好)PNG:映射为 compress_level(1→9,100→0) | 85 |
| method | str | 缩放时使用的插值算法。可选值: ["nearest", "bilinear", "bicubic", "lanczos"] | "lanczos" |
调用示例
Plain Text
1from __future__ import annotations
2
3import os
4import daft
5from daft import col
6
7from daft.aihc.common.udf import aihc_udf
8from daft.aihc.functions.image.image_compress import ImageCompress
9
10if __name__ == "__main__":
11 if os.getenv("DAFT_RUNNER", "native") == "ray":
12 import ray
13 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
14 daft.set_runner_ray()
15 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
16
17 samples = {
18 "image": [
19 "file:///local/sample_1.jpg",
20 "file:///mnt/pfs/sample_2.jpg",
21 "file:///mnt/bos/sample_3.jpg",
22 ],
23 "image_name": ["sample_1.jpg", "sample_2.jpg", "sample_3.jpg"],
24 }
25
26 ds = daft.from_pydict(samples)
27 ds = ds.with_column(
28 "image_compress",
29 aihc_udf(
30 ImageCompress,
31 construct_args={
32 "image_suffix": ".jpg",
33 "output_dir": "./test_images_output",
34 "image_src_type": "image_url",
35 "target_size": [200, 200],
36 "quality": 85,
37 "method": "lanczos",
38 },
39 batch_size=1,
40 )(col("image"), col("image_name")),
41 )
42 ds.show()
评价此篇文章
