理论成功

This commit is contained in:
2026-04-18 23:58:27 +08:00
parent 626a4ab2dc
commit 540bb96e55
6 changed files with 616 additions and 242 deletions
+30 -6
View File
@@ -4,6 +4,17 @@ from config import Config
from logger import logger
class ImageProcessor:
# 格式映射:将常见的小写格式名转换为 Pillow 可识别的格式名
FORMAT_MAP = {
'jpg': 'JPEG',
'jpeg': 'JPEG',
'png': 'PNG',
'webp': 'WEBP',
'gif': 'GIF',
'bmp': 'BMP',
'tiff': 'TIFF',
}
@staticmethod
def resize_by_ratio(img, ratio_width, ratio_height):
"""等比例缩放至目标比例(最长边适配)"""
@@ -31,20 +42,33 @@ class ImageProcessor:
@staticmethod
def convert_image(input_path, output_path, target_format, quality=None):
"""转换图片格式,可选缩放(尺寸解析在外部处理)"""
"""
转换图片格式
target_format: 小写字符串,如 'jpg', 'png', 'webp'
"""
try:
with Image.open(input_path) as img:
# 转换模式(RGBA转RGB对于JPEG
if target_format.lower() in ['jpg', 'jpeg'] and img.mode in ('RGBA', 'P'):
# 获取 Pillow 标准格式名
pillow_format = ImageProcessor.FORMAT_MAP.get(target_format.lower())
if pillow_format is None:
logger.error(f"不支持的输出格式: {target_format}")
return False
# 对于 JPEG 格式,需要处理透明通道
if pillow_format == 'JPEG' and img.mode in ('RGBA', 'P'):
rgb_img = Image.new('RGB', img.size, (255, 255, 255))
rgb_img.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
img = rgb_img
save_kwargs = {}
if target_format.lower() in ['jpg', 'jpeg', 'webp']:
if pillow_format in ('JPEG', 'WEBP'):
save_kwargs['quality'] = quality if quality is not None else Config.DEFAULT_QUALITY
img.save(output_path, format=target_format.upper(), **save_kwargs)
elif pillow_format == 'PNG':
save_kwargs['compress_level'] = 6
img.save(output_path, format=pillow_format, **save_kwargs)
logger.info(f"转换成功: {input_path} -> {output_path}")
return True
except Exception as e:
logger.error(f"转换失败 {input_path}: {e}")
return False
return False