Is there an obvious way to do this that I\'m missing? I\'m just trying to make thumbnails.
PIL already has the option to crop an image
img = ImageOps.fit(img, size, Image.ANTIALIAS)
If you don't want / don't have a need to open image with Pillow, use this:
from PIL import Image
new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))
Based in @tomvon, I finished using the following (pick your case):
a) Resizing height (I know the new width, so I need the new height)
new_width = 680
new_height = new_width * height / width
b) Resizing width (I know the new height, so I need the new width)
new_height = 680
new_width = new_height * width / height
Then just:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
Just updating this question with a more modern wrapper This library wraps Pillow (a fork of PIL) https://pypi.org/project/python-resize-image/
Allowing you to do something like this :-
from PIL import Image
from resizeimage import resizeimage
fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()
Heaps more examples in the above link.
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.
Have updated the answer above by "tomvon"
from PIL import Image
img = Image.open(image_path)
width, height = img.size[:2]
if height > width:
baseheight = 64
hpercent = (baseheight/float(img.size[1]))
wsize = int((float(img.size[0])*float(hpercent)))
img = img.resize((wsize, baseheight), Image.ANTIALIAS)
img.save('resized.jpg')
else:
basewidth = 64
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('resized.jpg')