python 图片缩放到指定像素
python 图片缩放到指定像素
from PIL import Image import io import base64 MAX_SIZE = 2450 def resize_image_max_side(image_data: bytes, max_side: int = MAX_SIZE) -> bytes: """ 图片缩放 :param image_data: :param max_side: :return: """ with Image.open(io.BytesIO(image_data)) as img: width, height = img.size max_dim = max(width, height) if max_dim > max_side: scale = max_side / max_dim new_size = (int(width * scale), int(height * scale)) img = img.resize(new_size, Image.LANCZOS) output = io.BytesIO() if img.mode == 'RGBA': # PNG 支持透明通道 img.save(output, format='PNG') else: # 确保非 RGBA 模式转为 RGB 再保存为 JPEG if img.mode != 'RGB': img = img.convert('RGB') img.save(output, format='JPEG') return output.getvalue() return image_data def process_image_segmentation(photo_data: bytes): """ 公共图像抠图处理逻辑 :param photo_data: 原图二进制数据 :param photo_type: 处理类型:matting or commonseg :param user_id: 当前用户 ID :return: dict 结果数据 """ photo_data = resize_image_max_side(photo_data, max_side=2450) if __name__ == '__main__': # 方法1: 通过request 的形式获取图片 request = "" photo = request.files.get("photo") # 通过request 的形式获取图片 photo_data = photo.read() process_image_segmentation(photo_data) # 方法2: 通过base64 的形式获取图片 photo_base64 = "" if photo_base64.startswith('data:image/'): splits = photo_base64.split('base64,', 1) if len(splits) == 2: photo_base64 = splits[1] photo_data = base64.b64decode(photo_base64) process_image_segmentation(photo_data)
浙公网安备 33010602011771号