Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Pillow: How to scale an image

Suppose I have an image which is 2322px x 4128px. How do I scale it so that both the width and height are both less than 1028px?

I won't be able to use Image.resize (https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize) since that requires me to give both the new width and height. What I plan to do is (pseudo code below):

if (image.width or image.height) > 1028:     if image.width > image.height:         tn_image = image.scale(make width of image 1028)         # since the height is less than the width and I am scaling the image         # and making the width less than 1028px, the height will surely be         # less than 1028px     else: #image's height is greater than it's width         tn_image = image.scale(make height of image 1028) 

I am guessing I need to use Image.thumbnail, but according to this example (http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails) and this answer (How do I resize an image using PIL and maintain its aspect ratio?), both the width and the height are provided in order to create the thumbnail. Is there any function which takes either the new width or the new height (not both) and scales the entire image?

like image 772
SilentDev Avatar asked Jul 14 '14 20:07

SilentDev


People also ask

How do you scale an image on a Pillow?

The Image module from pillow library has an attribute size. This tuple consists of width and height of the image as its elements. To resize an image, you call the resize() method of pillow's image class by giving width and height.

How do I resize an image to scale?

Step 1: Right-click on the image and select Open. If Preview is not your default image viewer, select Open With followed by Preview instead. Step 2: Select Tools on the menu bar. Step 3: Select Adjust Size on the drop-down menu.


2 Answers

Noo need to reinvent the wheel, there is the Image.thumbnail method available for this:

maxsize = (1028, 1028) image.thumbnail(maxsize, PIL.Image.ANTIALIAS) 

Ensures the resulting size is not bigger than the given bounds while maintains the aspect ratio.

Specifying PIL.Image.ANTIALIAS applies a high-quality downsampling filter for better resize result, you probably want that too.

like image 157
famousgarkin Avatar answered Sep 20 '22 17:09

famousgarkin


Use Image.resize, but calculate both width and height.

if image.width > 1028 or image.height > 1028:     if image.height > image.width:         factor = 1028 / image.height     else:         factor = 1028 / image.width     tn_image = image.resize((int(image.width * factor), int(image.height * factor))) 
like image 38
Sohcahtoa82 Avatar answered Sep 18 '22 17:09

Sohcahtoa82