Skip to content

Commit

Permalink
Bump quality value on resized JPEGs
Browse files Browse the repository at this point in the history
  • Loading branch information
ababic committed Jul 29, 2024
1 parent d66c6cf commit 56db87d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
22 changes: 16 additions & 6 deletions src/wagtail_bynder/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,19 +340,29 @@ def convert_downloaded_image(
format, mime-type and file size of the newly generated image without
having to perform any more file operations.
"""
original_width, original_height = self.width, self.height

# Filter.run() expects the object's width and height to reflect
# the image we're formatting, so we update them temporarily
self.width, self.height = utils.get_image_dimensions(source_file)
original_format, width, height, is_animated = (
utils.get_image_format_and_dimensions(source_file)
)

# Retreieve maximum height and width from settings
max_width = int(getattr(settings, "BYNDER_IMAGE_MAX_WIDTH", 3500))
max_height = int(getattr(settings, "BYNDER_IMAGE_MAX_HEIGHT", 3500))

filter_str = f"max-{max_width}x{max_height}"
output_format = utils.get_output_image_format(
original_format, is_animated=is_animated
)
if output_format == "jpeg":
# Since this will be a source image, use a higher JPEG quality than normal
filter_str += " jpegquality-90"

# Filter.run() expects the object's width and height to reflect
# the image we're formatting, so we update them temporarily
original_width, original_height = self.width, self.height
self.width, self.height = width, height
try:
# Use wagtail built-ins to resize/reformat the image
willow_image = Filter(f"max-{max_width}x{max_height}").run(
willow_image = Filter(filter_str).run(
self,
target_file,
source_file,
Expand Down
26 changes: 24 additions & 2 deletions src/wagtail_bynder/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,31 @@ def download_image(url: str) -> InMemoryUploadedFile:
return download_file(url, max_filesize, max_filesize_setting_name)


def get_image_dimensions(file: File) -> tuple[int, int]:
def get_image_format_and_dimensions(file: File) -> tuple[str, int, int, bool]:
willow_image = Image.open(file)
return willow_image.get_size()

return (
(willow_image.format_name,)
+ willow_image.get_size()
+ (willow_image.has_animation())
)


def get_output_image_format(original_format: str, *, is_animated: bool = False):
conversions = {
"avif": "png",
"bmp": "png",
"webp": "png",
}
if is_animated:
# Convert non-animated GIFs to PNG as well
conversions["gif"] = "png"

# Allow the user to override the conversions
custom_conversions = getattr(settings, "WAGTAILIMAGES_FORMAT_CONVERSIONS", {})
conversions.update(custom_conversions)

return conversions.get(original_format, original_format)


def filename_from_url(url: str) -> str:
Expand Down

0 comments on commit 56db87d

Please sign in to comment.