Search code examples
pythonimagepython-imaging-libraryimage-resizing

Scale images with a maximum limit for their number of pixels


I have lots of images in different shapes and sizes and I want to scale them in a way that the number of their pixels be smaller than a maximum. I also want to keep the aspect ratios of the original images. I came up with this:

from PIL import Image

img = Image.open("example.jpg")
max_pix = 65536

r = img.size[0] / img.size[1]
if r > 1:
    r **= -1  # because I don't know if the height is bigger or the width

n = int(sqrt(max_pix/r))
img.thumbnail((n, n))

img.save("example.jpg")

At most, r will be 1, so the number of pixels (n * n) will be equal to max_pix. Otherwise it will be smaller than that.
Is there a better way to do this? I'm gonna do this a lot of times, so I'm looking for the most efficient way.


Solution

  • If you are happy with the behaviour of your algorithm, I doubt the efficiency of those three or four lines of Python matters at all. Even though doing maths in Python is slow, it will be at least an order of magnitude (or likely more) faster than scaling 64K+ pixels anyway.

    If you're looking for a speed bump, you could check if there are faster alternatives to Pillow, such as Pillow-SIMD, and benchmark them for your use case.