Skip to content

Function to downscale to minimum size #7411

@gregorni

Description

@gregorni

What do you want to do?

I want to downscale/resize an image to a minimum size without changing its aspect ratio. This could be useful for shrinking large profile pictures, or shrinking an image to save processing time during future operations on an image.

How would you expect it to be implemented?

I'd like to call a function on an Image object, like downscale_to_min(img, min_width, min_height).

Example:

img = Image.open("filepath/to/my/picture.png")
print(img.size) # (1400, 100)
img.downscale_to_min(500, 500)
print(img.size) # (700, 500)

Any context?

There a similar function to this, thumbnail(), where you set the maximum size to scale an image to. It's like drawing a box around an image, and making sure no side of the image grows over the borders. I tried to visualize it here, red are the borders (the maximum size passed to thumbnail(), and green is the image:

Click to expand

Thumbnail

This function would be similar, except the box is now on the inside of the image, and the no side can shrink under the borders
Again, visualized:

Click to expand

Down to min

What are your OS, Python and Pillow versions?

  • OS: Fedora Linux 38
  • Python: 3.11
  • Pillow: 10.0.1

This is a basic function that implements the functionality using existing PIL functions.

def downscale_to_min(img, min_width, min_height):
    desired_ratio = min_height / min_width
    img_ratio = img.height / img.width

    if img_ratio > desired_ratio:
        desired_height = min_height
        downscale_factor = min_height / img.height
        desired_width = img.width * downscale_factor

    else:
        desired_width = min_width
        downscale_factor = min_width / img.width
        desired_height = img.height * downscale_factor

    img.resize((desired_width, desired_height))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions