import base64
import re
from io import BytesIO
from PIL import Image
class ImageScaleTool(object):
@classmethod
def base64_to_image(cls, base64_str) -> Image:
base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
byte_data = base64.b64decode(base64_data)
image_data = BytesIO(byte_data)
img = Image.open(image_data)
return img
@classmethod
def image_to_base64(cls, image: Image, img_format='png'):
container = BytesIO()
image.save(container, format(img_format))
data = base64.b64encode(container.getvalue()).decode()
return f'data:image/{img_format};base64,' + data
@classmethod
def scale_image(cls, image: Image, min_width, min_height) -> Image:
w, h = image.size
if w <= min_width and h <= min_height:
return image
if (1.0 * w / min_width) > (1.0 * h / min_height):
scale = 1.0 * w / min_width
new_im = image.resize((int(w / scale), int(h / scale)))
else:
scale = 1.0 * h / min_height
new_im = image.resize((int(w / scale), int(h / scale)))
return new_im
@classmethod
def scale_base64_img(cls, base64_str: str, width: int, height: int) -> str:
"""将base64图片缩放"""
if width <= 0 or height <= 0:
return ''
try:
image = cls.scale_image(cls.base64_to_image(base64_str), width, height)
res_str = cls.image_to_base64(image)
except Exception as e:
print('scale_base64_img error:', e)
return ''
return res_str
网友评论