Created
March 13, 2023 10:14
-
-
Save OndrejIT/5e32fb000cb8aec56e0ae12bd200bf45 to your computer and use it in GitHub Desktop.
auto_format.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author Ondrej Barta | |
# [email protected] | |
# Copyright 2023 | |
from thumbor.filters import BaseFilter, filter_method | |
from thumbor.utils import logger | |
# http://css.nothrem.cz/jak-urcit-kvalitu-a-kompresi-jpg-obrazku/ | |
# http://css.nothrem.cz/webp-a-avif/ | |
class Filter(BaseFilter): | |
@filter_method(BaseFilter.PositiveNumber, BaseFilter.DecimalNumber) | |
async def auto_format(self, base=90, quantifier=0.025): | |
accept = self.engine.context.request.headers.get("Accept", "") | |
if self.engine.avif_enabled() and "image/avif" in accept: | |
self.context.request.format = "avif" | |
recalculation = 0.70 | |
min_quality = 50 | |
elif "image/webp" in accept: | |
self.context.request.format = "webp" | |
recalculation = 1.1 | |
min_quality = 80 | |
else: | |
self.context.request.format = "jpeg" | |
recalculation = 1 | |
min_quality = 50 | |
image_w, image_h = self.engine.size | |
min_size = min(image_w, image_h) | |
quality = max(min_quality, (base - min_size * quantifier) * recalculation) | |
logger.debug(f"[AUTO FORMAT]: {self.context.request.format} - q: {quality}") | |
self.context.request.quality = round(quality) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment