75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
|
||
import base64
|
||
import io
|
||
from PIL import Image
|
||
|
||
class ImageUtils:
|
||
"""图片处理工具类"""
|
||
|
||
@staticmethod
|
||
def resize_image(image_path, max_size=(1024, 1024)):
|
||
"""
|
||
调整图片大小,确保不超过最大尺寸
|
||
|
||
Args:
|
||
image_path: 图片路径
|
||
max_size: 最大尺寸 (宽, 高)
|
||
|
||
Returns:
|
||
PIL.Image: 调整大小后的图片对象
|
||
"""
|
||
img = Image.open(image_path)
|
||
img.thumbnail(max_size, Image.LANCZOS)
|
||
return img
|
||
|
||
@staticmethod
|
||
def convert_to_base64(image, format='JPEG'):
|
||
"""
|
||
将PIL图片对象转换为base64编码
|
||
|
||
Args:
|
||
image: PIL图片对象
|
||
format: 图片格式,如'JPEG', 'PNG'
|
||
|
||
Returns:
|
||
str: base64编码的图片数据
|
||
"""
|
||
buffer = io.BytesIO()
|
||
image.save(buffer, format=format)
|
||
img_str = base64.b64encode(buffer.getvalue())
|
||
return img_str
|
||
|
||
@staticmethod
|
||
def image_to_base64(image_path, max_size=(1024, 1024), format='JPEG'):
|
||
"""
|
||
将图片文件转换为base64编码,并可选调整大小
|
||
|
||
Args:
|
||
image_path: 图片路径
|
||
max_size: 最大尺寸 (宽, 高)
|
||
format: 图片格式,如'JPEG', 'PNG'
|
||
|
||
Returns:
|
||
str: base64编码的图片数据
|
||
"""
|
||
img = ImageUtils.resize_image(image_path, max_size)
|
||
return ImageUtils.convert_to_base64(img, format)
|
||
|
||
@staticmethod
|
||
def base64_to_image(base64_str):
|
||
"""
|
||
将base64编码转换为PIL图片对象
|
||
|
||
Args:
|
||
base64_str: base64编码的图片数据
|
||
|
||
Returns:
|
||
PIL.Image: 图片对象
|
||
"""
|
||
img_data = base64.b64decode(base64_str)
|
||
buffer = io.BytesIO(img_data)
|
||
img = Image.open(buffer)
|
||
return img
|