pflaenz.li/pflaenzli/pflaenzli/utils/compress_image.py
Jannis Portmann 8d8e1b69d7
Some checks failed
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is failing
continuous-integration/drone/promote/production Build is passing
Compress images when uploaded
2023-07-18 17:03:19 +02:00

38 lines
1.3 KiB
Python

import sys
from io import BytesIO
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile
from pflaenzli_django.settings import IMAGE_MAX_SIZE, IMAGE_QUALITY
def compress_image(image, path):
tmp_img = Image.open(image)
fmt = tmp_img.format
if fmt not in ['JPEG', 'PNG']:
raise TypeError(f'Invalid image format: {fmt}')
width, height = tmp_img.size
compressed_width, compressed_height = get_compressed_size(width, height)
tmp_img_resized = tmp_img.resize((compressed_width, compressed_height))
outputIoStream = BytesIO()
tmp_img_resized.save(outputIoStream, format=fmt, quality=IMAGE_QUALITY)
outputIoStream.seek(0)
return InMemoryUploadedFile(file=outputIoStream, field_name='ImageField',
content_type=f'image/{fmt.lower()}', name=path, size=sys.getsizeof(outputIoStream),
charset=None)
def get_compressed_size(width, height):
if width > height:
compressed_width = min(width, IMAGE_MAX_SIZE)
compressed_height = int(compressed_width * (height / width))
else:
compressed_height = min(height, IMAGE_MAX_SIZE)
compressed_width = int(compressed_height * (width / height))
return compressed_width, compressed_height