Home » Various pillow examples in python

Various pillow examples in python

Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification
Spring Framework Basics Video Course
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests

The Python Imaging Library is ideal for image archival and batch processing applications.

You can use the library to create thumbnails, convert between file formats, print images etc.

Pillow offers several standard procedures for image manipulation. These include:

  • per-pixel manipulations,
  • masking and transparency handling,
  • image filtering, such as blurring, contouring, smoothing, or edge finding,
  • image enhancing, such as sharpening, adjusting brightness, contrast or color,
  • adding text to images and much more.

Some of the file formats supported are PPM, PNG, JPEG, GIF, TIFF, and BMP. It is also possible to create new file decoders to expand the library of file formats accessible.

Install Pillow

To install pillow in Python using pip, open command prompt or terminal and run the following command.

pip install Pillow

Code

Show an image

The Image.open() method reads the image file. Pillow can read over 30 different file formats.

The show() method saves the image into a temporary file and displays it in an external program.

#!/usr/bin/python

from PIL import Image
import sys

try:
    im = Image.open("test.png")

except IOError:
    print("Unable to load image")
    sys.exit(1)
    
im.show()

Get the size of an image

from PIL import Image

#read the image
im = Image.open("test.png")

#image size
width = im.size[0]
height = im.size[1]

print('Width  of the image is:', width)
print('Height of the image is:', height)

Resize an image

In the following example, we will read an image and resize it to (200, 200).

from PIL import Image

#read the image
im = Image.open("test.png")

#image size
size=(200,200)
#resize image
out = im.resize(size)
#save resized image
out.save('resize-test.png')

Rotate image

In the following example, we will rotate the image by 90 degrees.

from PIL import Image

#read the image
im = Image.open("test.png")

#rotate image
out = im.rotate(90)
out.save('rotate-test.png')

Converting image with Pillow

With the save() method, we can convert an image to a different format.

#!/usr/bin/python

from PIL import Image
import sys

try:
    im = Image.open("test.jpg")

except IOError:
    print("Unable to load image")
    sys.exit(1)

im.save('test.png', 'png')

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More