This repository has been archived on 2023-09-24. You can view files and clone it, but cannot push or open issues or pull requests.
takahe/core/files.py

68 lines
1.9 KiB
Python
Raw Normal View History

2022-12-02 02:46:49 +01:00
import io
import blurhash
2022-12-15 08:50:54 +01:00
import httpx
from django.conf import settings
2022-12-02 02:46:49 +01:00
from django.core.files import File
2022-12-15 08:50:54 +01:00
from django.core.files.base import ContentFile
2022-12-02 02:46:49 +01:00
from PIL import Image, ImageOps
2022-12-04 18:46:41 +01:00
def resize_image(
image: File,
*,
size: tuple[int, int],
cover=True,
keep_format=False,
) -> File:
2022-12-02 02:46:49 +01: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 18:46:41 +01:00
if cover:
resized_image = ImageOps.fit(img, size)
else:
resized_image = ImageOps.contain(img, size)
2022-12-02 02:46:49 +01:00
new_image_bytes = io.BytesIO()
2022-12-04 18:46:41 +01: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 02:46:49 +01:00
2022-12-11 20:37:28 +01:00
def blurhash_image(file) -> str:
2022-12-02 02:46:49 +01:00
"""
Returns the blurhash for an image
"""
2022-12-11 20:37:28 +01:00
return blurhash.encode(file, 4, 4)
2022-12-15 08:50:54 +01:00
async def get_remote_file(
url: str,
*,
timeout: float = settings.SETUP.REMOTE_TIMEOUT,
max_size: int | None = None,
) -> tuple[File | None, str | None]:
"""
Download a URL and return the File and content-type.
"""
async with httpx.AsyncClient() as client:
async with client.stream("GET", url, timeout=timeout) as stream:
allow_download = max_size is None
if max_size:
try:
content_length = int(stream.headers["content-length"])
allow_download = content_length <= max_size
except TypeError:
pass
if allow_download:
file = ContentFile(await stream.aread(), name=url)
return file, stream.headers["content-type"]
return None, None