29 lines
862 B
Python
29 lines
862 B
Python
from base64 import b64encode
|
|
from io import BytesIO
|
|
from PIL import Image
|
|
from typing import Optional
|
|
|
|
|
|
def encode_image(image: bytes) -> str:
|
|
encoded_image = b64encode(image).decode('utf-8')
|
|
return f"data:image/jpeg;base64,{encoded_image}"
|
|
|
|
|
|
def compress_image(image: bytes, max_side: Optional[int] = None) -> bytes:
|
|
img = Image.open(BytesIO(image)).convert("RGB")
|
|
|
|
if max_side is not None and (img.width > max_side or img.height > max_side):
|
|
scale = min(max_side / img.width, max_side / img.height)
|
|
new_width = int(img.width * scale)
|
|
new_height = int(img.height * scale)
|
|
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
|
|
output = BytesIO()
|
|
img.save(output, format='JPEG', quality=87, optimize=True)
|
|
return output.getvalue()
|
|
|
|
|
|
__all__ = [
|
|
"compress_image",
|
|
"encode_image"
|
|
]
|