One important hint, though: Replace im.thumbnail(size)īy default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality. I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you. Img = img.resize((basewidth,hsize), Image.ANTIALIAS) The size of the thumbnail will be the largest size that preserves the aspect ratio such. Hsize = int((float(img.size)*float(wpercent))) In the following example, we create a thumbnail from the image img. You’ll also learn how to specify a percentage to scale by, a maximum width, and a maximum height. Change "basewidth" to any other number to change the default width of your images. Syntax: Image. Image.resize() Returns a resized copy of this image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. It does this by determining what percentage 300 pixels is of the original width (img.size) and then multiplying the original height (img.size) by that percentage. The Image module provides a class with the same name which is used to represent a PIL image. 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. from PIL import Image basewidth 300 img Image.open ('somepic.jpg') wpercent basewidth / float (img.size 0) hsize int (float (img.size 1) float (wpercent)) img img.resize ( (basewidth, hsize), Image.ANTIALIAS) img.save ('somepic. Print "cannot create thumbnail for '%s'" % infile To resize an image using PIL and maintain its aspect ratio with Python, we can use the resize method. Ive attached the method where I resize the image and the main function. Outfile = os.path.splitext(infile) + ".thumbnail" There is of course also a library method to do this: the method Image.thumbnail.īelow is an (edited) example from the PIL documentation. Rescale an image so that maximum side is equal to maxsize, keeping the aspect ratio of the initial image. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height). from PIL import Image basewidth 300 img Image.open ('somepic.jpg') wpercent basewidth / float (img.size 0) hsize int (float (img.size 1) float (wpercent)) img img.resize ( (basewidth, hsize), Image.ANTIALIAS) img.save ('somepic.jpg') to open the image at the given path with Image.open.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |