hutool.core.util.image¶
图片工具类
提供图片格式检测功能(通过文件头魔数)以及图片操作(缩放、颜色替换、水印、人脸检测)。 格式检测为纯标准库实现;图片操作依赖 Pillow,以 try…except ImportError 保护。
Module Contents¶
Classes¶
图片工具类,提供图片格式检测和基础操作。 |
API¶
- class hutool.core.util.image.ImageUtil¶
图片工具类,提供图片格式检测和基础操作。
- _MAGIC_TABLE = ((b'\xff\xd8\xff', 'jpg'), (b'\x89PNG\r\n\x1a\n', 'png'), (b'GIF87a', 'gif'), (b'GIF89a', 'gif'), (b...¶
- static detect_image_type(file_or_bytes: Union[str, bytes, bytearray]) Optional[str]¶
通过文件头魔数检测图片格式。
支持 JPEG、PNG、GIF、BMP、TIFF、WebP。
- 参数:
file_or_bytes – 文件路径(str)或原始字节数据
- 返回:
图片格式字符串(
"jpg"/"png"/"gif"/"bmp"/"tiff"/"webp"),无法识别时返回None
>>> ImageUtil.detect_image_type(b'\x89PNG\r\n\x1a\n...') 'png' >>> ImageUtil.detect_image_type(b'random data') is None True
- static resize_image(file_or_bytes: Union[str, bytes], width: int, height: int, output_path: Optional[str] = None) Union[bytes, str]¶
缩放图片到指定尺寸。
需要安装 Pillow(
pip install Pillow)。- 参数:
file_or_bytes – 图片文件路径或字节数据
width – 目标宽度
height – 目标高度
output_path – 输出文件路径,为
None时返回 bytes
- 返回:
缩放后的图片字节数据或输出文件路径
- 抛出:
ImportError – 未安装 Pillow 时
- static replace_color(file_or_bytes: Union[str, bytes], target_color: tuple, replacement_color: tuple, tolerance: int = 30, output_path: Optional[str] = None) Union[bytes, str]¶
替换图片中的指定颜色。
需要安装 Pillow(
pip install Pillow)。- 参数:
file_or_bytes – 图片文件路径或字节数据
target_color – 目标颜色,RGB 元组如
(255, 0, 0)replacement_color – 替换颜色,RGB 元组如
(0, 255, 0)tolerance – 颜色容差,默认 30
output_path – 输出文件路径,为
None时返回 bytes
- 返回:
替换后的图片字节数据或输出文件路径
- 抛出:
ImportError – 未安装 Pillow 时
- static add_watermark(file_or_bytes: Union[str, bytes], text: str, position: Optional[tuple] = None, color: tuple = (255, 255, 255), font_size: int = 36, output_path: Optional[str] = None) Union[bytes, str]¶
为图片添加文字水印。
需要安装 Pillow(
pip install Pillow)。- 参数:
file_or_bytes – 图片文件路径或字节数据
text – 水印文字
position – 水印位置
(x, y),为None时默认右下角color – 文字颜色 RGB 元组,默认白色
(255, 255, 255)font_size – 字体大小,默认 36
output_path – 输出文件路径,为
None时返回 bytes
- 返回:
添加水印后的图片字节数据或输出文件路径
- 抛出:
ImportError – 未安装 Pillow 时
- static face_detect(file_or_bytes: Union[str, bytes]) list¶
检测图片中的人脸位置。
需要安装 Pillow(
pip install Pillow)。 使用 Haar 级联分类器(OpenCV 内置的haarcascade_frontalface_default.xml)。- 参数:
file_or_bytes – 图片文件路径或字节数据
- 返回:
人脸位置列表,每个元素为
(x, y, w, h)元组;无法检测时返回空列表- 抛出:
ImportError – 未安装 Pillow 或 opencv-python 时