Using the Python Image Library (PIL) you can resize an image. Several filters can be specified. ANTIALIAS is best for downsampling, the other filters work better with upsampling (increasing the size). In this code snippet one image of each filter option is saved, so you can compare the quality in your favorite image viewer. Also an alternative to the PIL show() function is given. This way you can avoid the clutter of bitmap files generated by PIL and left behind in your \Local Settings\Temp folder.
Resize an Image (Python)
# resize an image using the PIL image library
# free from: http://www.pythonware.com/products/pil/index.htm
# tested with Python24 vegaseat 11oct2005
import Image
# open an image file (.bmp,.jpg,.png,.gif) you have in the working folder
imageFile = "zFlowers.jpg"
im1 = Image.open(imageFile)
# adjust width and height to your needs
width = 500
height = 420
# use one of these filter options to resize the image
im2 = im1.resize((width, height), Image.NEAREST) # use nearest neighbour
im3 = im1.resize((width, height), Image.BILINEAR) # linear interpolation in a 2x2 environment
im4 = im1.resize((width, height), Image.BICUBIC) # cubic spline interpolation in a 4x4 environment
im5 = im1.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
ext = ".jpg"
im2.save("NEAREST" + ext)
im3.save("BILINEAR" + ext)
im4.save("BICUBIC" + ext)
im5.save("ANTIALIAS" + ext)
# optional image viewer ...
# image viewer i_view32.exe free download from: http://www.irfanview.com/
# avoids the many huge bitmap files generated by PIL's show()
import os
os.system("d:/python24/i_view32.exe %s" % "BILINEAR.jpg")
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Christian Harms 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
silverspoon 0 Newbie Poster
LaurieW 0 Newbie Poster
HiHe 174 Junior Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
krystosan 0 Junior Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
krystosan 0 Junior Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
krystosan 0 Junior Poster
eplimish 0 Newbie Poster
Budy_1
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.