MatrixGPT/matrix_gpt/image.py

26 lines
822 B
Python
Raw Normal View History

2024-04-10 18:21:26 -06:00
import asyncio
2024-04-09 19:26:44 -06:00
import base64
import io
from PIL import Image
2024-04-10 18:21:26 -06:00
async def process_image(source_bytes: bytes, resize_px: int):
loop = asyncio.get_event_loop()
image = await loop.run_in_executor(None, Image.open, io.BytesIO(source_bytes))
2024-04-09 19:26:44 -06:00
width, height = image.size
if min(width, height) > resize_px:
if width < height:
new_width = resize_px
new_height = int((height / width) * new_width)
else:
new_height = resize_px
new_width = int((width / height) * new_height)
2024-04-10 18:21:26 -06:00
image = await loop.run_in_executor(None, image.resize, (new_width, new_height))
2024-04-09 19:26:44 -06:00
byte_arr = io.BytesIO()
2024-04-10 18:21:26 -06:00
await loop.run_in_executor(None, image.save, byte_arr, 'PNG')
2024-04-09 19:26:44 -06:00
image_bytes = byte_arr.getvalue()
return base64.b64encode(image_bytes).decode('utf-8')