Skip to content

Commit

Permalink
constrain maximum JPEG dimensions
Browse files Browse the repository at this point in the history
JPEG uses 2 bytes to store width and height, so the maximum dimension
of either is 65,535. libjpeg and derivatives use a maximum dimension
size of 65,500, and that is used by pillow. When creating a jpeg,
clamp the maximum dimmension to 65,000 whether we requested resizing
or not.
  • Loading branch information
irv committed Jan 23, 2024
1 parent b697d84 commit 809ccaa
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion image_processing/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from image_processing import utils
from image_processing.exceptions import ImageProcessingError

MAX_JPEG_DIMENSION = 65500

class Converter(object):
"""
Expand Down Expand Up @@ -50,8 +51,13 @@ def convert_to_jpg(self, input_filepath, output_filepath, resize=None, quality=N
self.logger.warning(
'Image is RGBA - the alpha channel will be removed from the JPEG derivative image')
input_pil = input_pil.convert(mode="RGB")
# libjpeg has a maximum dimension of 65,500, which is lower than the actual maximum jpeg dimension of 65,535
# JPEG2000 does not have the restriction
# if we're not already scaling the jpeg, then clamp the thumbnail to the max supported dimensions
if resize is None and MAX_JPEG_DIMENSION <= max(input_pil.size):
resize = 1.0
if resize:
thumbnail_size = tuple(int(i * resize) for i in input_pil.size)
thumbnail_size = tuple(min(int(i * resize), MAX_JPEG_DIMENSION) for i in input_pil.size)
input_pil.thumbnail(thumbnail_size, Image.Resampling.LANCZOS)
if quality:
input_pil.save(output_filepath, "JPEG", quality=quality, icc_profile=icc_profile)
Expand Down

0 comments on commit 809ccaa

Please sign in to comment.