How do I resize an image using PIL and maintain its aspect ratio?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Realization
--
Chapters
00:00 How Do I Resize An Image Using Pil And Maintain Its Aspect Ratio?
00:15 Accepted Answer Score 631
00:50 Answer 2 Score 39
01:07 Answer 3 Score 408
01:45 Answer 4 Score 91
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/2739...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #image #pythonimaginglibrary #thumbnails
#avk47
ACCEPTED ANSWER
Score 631
Define a maximum size.
Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).
The proper size is oldsize*ratio.
There is of course also a library method to do this: the method Image.thumbnail.
Below is an (edited) example from the PIL documentation.
import os, sys
import Image
size = 128, 128
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail"
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.Resampling.LANCZOS)
im.save(outfile, "JPEG")
except IOError:
print "cannot create thumbnail for '%s'" % infile
ANSWER 2
Score 408
This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width img.size[0] and then multiplying the original height img.size[1] by that percentage. Change base_width to any other number to change the default width of your images.
from PIL import Image
base_width = 300
img = Image.open('somepic.jpg')
wpercent = (base_width / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((base_width, hsize), Image.Resampling.LANCZOS)
img.save('somepic.jpg')
ANSWER 3
Score 91
I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you.
One important hint, though: Replace
im.thumbnail(size)
with
im.thumbnail(size,Image.ANTIALIAS)
by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.
ANSWER 4
Score 39
If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?
For example, half the original size
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )