调整图像尺寸 Args: image: 输入图像 target_size: 目标尺寸 (width, height) keep_aspect_ratio: 是否保持宽高比 resample: 重采样方法 Returns: 调整尺寸后的图像 Raises: ImageProcessError: 当处理失败时
(image: Image.Image, target_size: Tuple[int, int],
keep_aspect_ratio: bool = False,
resample: int = Image.LANCZOS)
| 20 | |
| 21 | @staticmethod |
| 22 | def resize_image(image: Image.Image, target_size: Tuple[int, int], |
| 23 | keep_aspect_ratio: bool = False, |
| 24 | resample: int = Image.LANCZOS) -> Image.Image: |
| 25 | """ |
| 26 | 调整图像尺寸 |
| 27 | |
| 28 | Args: |
| 29 | image: 输入图像 |
| 30 | target_size: 目标尺寸 (width, height) |
| 31 | keep_aspect_ratio: 是否保持宽高比 |
| 32 | resample: 重采样方法 |
| 33 | |
| 34 | Returns: |
| 35 | 调整尺寸后的图像 |
| 36 | |
| 37 | Raises: |
| 38 | ImageProcessError: 当处理失败时 |
| 39 | """ |
| 40 | try: |
| 41 | if keep_aspect_ratio: |
| 42 | # 计算保持宽高比的尺寸 |
| 43 | original_width, original_height = image.size |
| 44 | target_width, target_height = target_size |
| 45 | |
| 46 | # 计算缩放比例 |
| 47 | width_ratio = target_width / original_width |
| 48 | height_ratio = target_height / original_height |
| 49 | scale_ratio = min(width_ratio, height_ratio) |
| 50 | |
| 51 | # 计算新尺寸 |
| 52 | new_width = int(original_width * scale_ratio) |
| 53 | new_height = int(original_height * scale_ratio) |
| 54 | |
| 55 | return image.resize((new_width, new_height), resample) |
| 56 | else: |
| 57 | return image.resize(target_size, resample) |
| 58 | |
| 59 | except Exception as e: |
| 60 | raise ImageProcessError(f"图像尺寸调整失败: {str(e)}") from e |
| 61 | |
| 62 | @staticmethod |
| 63 | def convert_to_grayscale(image: Image.Image) -> Image.Image: |
no test coverage detected