summaryrefslogtreecommitdiffstats
path: root/core
diff options
context:
space:
mode:
authorAndrew Godwin2022-12-04 10:46:41 -0700
committerAndrew Godwin2022-12-04 10:46:41 -0700
commitc3d4d0f547d1971f35b919a15ec65be548f2a52d (patch)
tree379466af391dac607dc667fb015a36e37a070a5b /core
parentffda9c4913370ee84fa156e4fff07913b6d9448f (diff)
downloadtakahe-c3d4d0f547d1971f35b919a15ec65be548f2a52d.tar.gz
takahe-c3d4d0f547d1971f35b919a15ec65be548f2a52d.tar.bz2
takahe-c3d4d0f547d1971f35b919a15ec65be548f2a52d.zip
Image upload polishing and webp
Diffstat (limited to 'core')
-rw-r--r--core/files.py23
1 files changed, 19 insertions, 4 deletions
diff --git a/core/files.py b/core/files.py
index c4f4355..4c7729d 100644
--- a/core/files.py
+++ b/core/files.py
@@ -5,16 +5,31 @@ from django.core.files import File
from PIL import Image, ImageOps
-def resize_image(image: File, *, size: tuple[int, int]) -> File:
+def resize_image(
+ image: File,
+ *,
+ size: tuple[int, int],
+ cover=True,
+ keep_format=False,
+) -> File:
"""
Resizes an image to fit insize the given size (cropping one dimension
to fit if needed)
"""
with Image.open(image) as img:
- resized_image = ImageOps.fit(img, size)
+ if cover:
+ resized_image = ImageOps.fit(img, size)
+ else:
+ resized_image = ImageOps.contain(img, size)
new_image_bytes = io.BytesIO()
- resized_image.save(new_image_bytes, format=img.format)
- return File(new_image_bytes)
+ 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
def blurhash_image(image) -> str: