从多种输入格式加载图片 Args: img_input: 图片输入,支持bytes、base64字符串、文件路径、PIL Image对象或numpy数组 Returns: PIL Image对象 Raises: ImageProcessError: 当图片加载失败时
(img_input: Union[bytes, str, pathlib.PurePath, Image.Image, np.ndarray])
| 80 | |
| 81 | |
| 82 | def load_image_from_input(img_input: Union[bytes, str, pathlib.PurePath, Image.Image, np.ndarray]) -> Image.Image: |
| 83 | """ |
| 84 | 从多种输入格式加载图片 |
| 85 | |
| 86 | Args: |
| 87 | img_input: 图片输入,支持bytes、base64字符串、文件路径、PIL Image对象或numpy数组 |
| 88 | |
| 89 | Returns: |
| 90 | PIL Image对象 |
| 91 | |
| 92 | Raises: |
| 93 | ImageProcessError: 当图片加载失败时 |
| 94 | """ |
| 95 | try: |
| 96 | if isinstance(img_input, bytes): |
| 97 | return Image.open(io.BytesIO(img_input)) |
| 98 | elif isinstance(img_input, Image.Image): |
| 99 | return img_input.copy() |
| 100 | elif isinstance(img_input, np.ndarray): |
| 101 | return _numpy_to_pil_image(img_input) |
| 102 | elif isinstance(img_input, str): |
| 103 | # 先尝试作为文件路径,如果失败则作为base64 |
| 104 | if os.path.exists(img_input): |
| 105 | return Image.open(img_input) |
| 106 | else: |
| 107 | return base64_to_image(img_input) |
| 108 | elif isinstance(img_input, pathlib.PurePath): |
| 109 | return Image.open(img_input) |
| 110 | else: |
| 111 | supported_types = (bytes, str, pathlib.PurePath, Image.Image, np.ndarray) |
| 112 | raise ImageProcessError( |
| 113 | f"不支持的图片输入类型: {type(img_input)}。" |
| 114 | f"支持的类型: {supported_types}" |
| 115 | ) |
| 116 | except ImageProcessError: |
| 117 | raise |
| 118 | except Exception as e: |
| 119 | raise ImageProcessError(f"图片加载失败: {str(e)}") from e |
| 120 | |
| 121 | |
| 122 | def _numpy_to_pil_image(array: np.ndarray) -> Image.Image: |
no test coverage detected
searching dependent graphs…