-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimage_processor.py
34 lines (28 loc) · 1003 Bytes
/
image_processor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from io import BytesIO
from PIL import Image, ImageFile
from typing import Optional
ImageFile.LOAD_TRUNCATED_IMAGES = True
def process_image(content: bytes):
img = Image.open(BytesIO(content))
width, height = img.size
aspect_ratio = width / height
new_height = 200
new_width = int(aspect_ratio * new_height)
new_image = img.resize((new_width, new_height))
return img, new_image
def resize_image(
content: bytes, req_height: Optional[str], req_width: Optional[str]
) -> BytesIO:
img = Image.open(BytesIO(content)) # noqa
width, height = img.size
aspect_ratio = width / height
if req_height:
req_width = int(int(req_height) * aspect_ratio)
elif req_width:
req_height = int(int(req_width) * 1 / aspect_ratio)
else:
req_width, req_height = width, height
new_image = img.resize((int(req_width), int(req_height)))
output_buffer = BytesIO()
new_image.save(output_buffer, format="JPEG")
return output_buffer