3

I'm trying to resize an image maintaining its aspect ratio such that its smallest size is 500px.

Using the code from this answer works, but it resize the image based on largest size.

So if we have a 2000x1000 image and we set size= 500,500 the resulting image will be 500x250, while I desire 1000x500. How can I do it?

Obviously these are random numbers.

Community
  • 1
  • 1
justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

1 Answers1

4

Use max instead of min. Observe the different results:

>>> maxwidth = 500
>>> maxheight = 500
>>> width = 2000
>>> height = 1000
>>> i = min(maxwidth/width, maxheight/height)
>>> a = max(maxwidth/width, maxheight/height)
>>> width*i, height*i
(500.0, 250.0)
>>> width*a, height*a
(1000.0, 500.0)

You can use these values to determine what size you should be sending to img.thumbnail:

x,y = 500, 500
# compute i and a above
m.thumbnail((x*a/i, y*a/i), Image.ANTIALIAS)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97