2022-12-02 01:46:49 +00:00
|
|
|
import io
|
|
|
|
|
|
|
|
import blurhash
|
|
|
|
from django.core.files import File
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
|
|
|
|
|
2022-12-04 17:46:41 +00:00
|
|
|
def resize_image(
|
|
|
|
image: File,
|
|
|
|
*,
|
|
|
|
size: tuple[int, int],
|
|
|
|
cover=True,
|
|
|
|
keep_format=False,
|
|
|
|
) -> File:
|
2022-12-02 01:46:49 +00:00
|
|
|
"""
|
|
|
|
Resizes an image to fit insize the given size (cropping one dimension
|
|
|
|
to fit if needed)
|
|
|
|
"""
|
|
|
|
with Image.open(image) as img:
|
2022-12-04 17:46:41 +00:00
|
|
|
if cover:
|
|
|
|
resized_image = ImageOps.fit(img, size)
|
|
|
|
else:
|
|
|
|
resized_image = ImageOps.contain(img, size)
|
2022-12-02 01:46:49 +00:00
|
|
|
new_image_bytes = io.BytesIO()
|
2022-12-04 17:46:41 +00:00
|
|
|
if keep_format:
|
|
|
|
resized_image.save(new_image_bytes, format=image.format)
|
|
|
|
file = File(new_image_bytes)
|
|
|
|
else:
|
|
|
|
resized_image.save(new_image_bytes, format="webp")
|
|
|
|
file = File(new_image_bytes, name="image.webp")
|
|
|
|
file.image = resized_image
|
|
|
|
return file
|
2022-12-02 01:46:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
def blurhash_image(image) -> str:
|
|
|
|
"""
|
|
|
|
Returns the blurhash for an image
|
|
|
|
"""
|
|
|
|
return blurhash.encode(image, 4, 4)
|