Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pillow Getting Started Examples

Pillow Getting Started Examples

Using Pillow, you can import the main modules of Pillow in the following ways:



from PIL import Image, ImageFilter, ImageDraw, ImageFont

Pillow maintains API compatibility with PIL, which means most code written for PIL can be used directly with Pillow, just change the import statement from import PIL to from PIL import ....


Basic Image Operations

Load and Display an Image

Test image (download to local for testing):

Example

from

PIL

import

Image

Open an image (supports JPEG, PNG, GIF, etc.)

img

=

Image.

open

(

"tiger.jpeg"

)

 

Display the image (system default image viewer)

img.

show

(

)

 

Get image information

print

(

"Format:"

,

img.

format

)

 

JPEG/PNG

print

(

"Size:"

,

img.

size

)

   

(width, height)

print

(

"Pattern:"

,

img.

mode

)

 

RGB/L/CMYK

Example output:

格式: JPEG

尺寸: (987, 987)

模式: RGB

Analysis:

Save the image

The following code saves the image as files in different formats: one converted to a PNG format "example.png" file, and one "example_quality.jpg" file with JPEG quality specified as 95.

Example

from

PIL

import

Image

Open an image (supports JPEG, PNG, GIF, etc.)

img

=

Image.

open

(

"tiger.jpeg"

)

 

Display the image (system default image viewer)

img.

show

(

)

 

Get image information

print

(

"Format:"

,

img.

format

)

 

JPEG/PNG

print

(

"Size:"

,

img.

size

)

   

(width, height)

print

(

"Pattern:"

,

img.

mode

)

 

RGB/L/CMYK

Save in Different Formats

img.

save

(

'example.png'

)

 

Convert to PNG format

img.

save

(

'example_quality.jpg'

,

quality

=

95

)

 

Specify JPEG quality

Image Format Conversion

Example

from

PIL

import

Image

img

=

Image.

open

(

"tiger.jpeg"

)

 

Convert to grayscale

gray_img

=

img.

convert

(

"L"

)

 

gray_img.

save

(

"tiger_gray.png"

)

 

Save as PNG

Convert to RGB (even if the original image is RGBA)

rgb_img

=

img.

convert

(

"RGB"

)

 

rgb_img.

save

(

"tiger_rgb.jpg"

,

quality

=

95

)

 

Quality parameter (1-100)


Image Processing Operations

Resize the image

Set a fixed height and width:

Example

from

PIL

import

Image

img

=

Image.

open

(

"tiger.jpg"

)

Resize

resized_img

=

img.

resize

(

(

400

,

300

)

)

 

resized_img.

save

(

"cat_small.jpg"

)

Generate a thumbnail (preserving proportions)

img.

thumbnail

(

(

200

,

200

)

)

 

Modify in place

img.

save

(

"cat_thumbnail.jpg"

)

Scale proportionally

Set the ratio:

Example

from

PIL

import

Image

Open an image (supports JPEG, PNG, GIF, etc.)

img

=

Image.

open

(

"tiger.jpeg"

)

 

Scale proportionally

width

,

height

=

img.

size

scaled_image

=

img.

resize

(

(

width//

2

,

height//

2

)

)

scaled_image.

show

(

)

Crop and Rotate an Image

Example

from

PIL

import

Image

img

=

Image.

open

(

"tiger.jpeg"

)

Crop (left, top, right, bottom)

cropped_img

=

img.

crop

(

(

100

,

100

,

500

,

400

)

)

 

cropped_img.

save

(

""

tiger_cropped.

jpg

")

Rotate (counterclockwise 90 degrees)

rotated_img = img.rotate(90, expand=True) # expand prevents cropping
rotated_img.save("

"tiger_rotated.jpg"

)

The cropped image is as follows:

The rotated image is as follows:


Image Enhancement and Filters

Apply filters

Example

from

PIL

import

Image

,

ImageFilter

img

=

Image.

open

(

"tiger.jpeg"

)

Blur filter

blurred_image

=

img.

filter

(

ImageFilter.

BLUR

)

blurred_image.

show

(

)

Edge enhancement

edge_enhanced

=

img.

filter

(

ImageFilter.

EDGE_ENHANCE

)

edge_enhanced.

show

(

)

Adjust Brightness and Contrast

Example

from

PIL

import

Image

,

ImageEnhance

img

=

Image.

open

(

"tiger.jpeg"

)

Enhance brightness

enhancer

=

ImageEnhance.

Brightness

(

img

)

bright_image

=

enhancer.

enhance

(

1.5

)

 

1.5x brightness

bright_image.

show

(

)

Enhance contrast

enhancer

=

ImageEnhance.

Contrast

(

img

)

contrast_image

=

enhancer.

enhance

(

2.0

)

 

2x contrast

contrast_image.

show

(

)


Draw on an Image

Draw Basic Shapes

Example

from

PIL

import

Image

,

ImageDraw

img

=

Image.

open

(

"tiger.jpeg"

)

Create a drawing object

draw

=

ImageDraw.

Draw

(

img

)

Draw a rectangle

draw.

rectangle

(

[

(

100

,

100

)

,

(

300

,

300

)

]

,

outline

=

"red"

,

width

=

5

)

Draw a Line

draw.

line

(

[

(

0

,

0

)

,

(

500

,

500

)

]

,

fill

=

"blue"

,

width

=

3

)

Draw a circle

draw.

ellipse

(

[

(

200

,

200

)

,

(

400

,

400

)

]

,

outline

=

"green"

,

width

=

4

)

img.

show

(

)

The generated image is as follows:

Add Text

You can add text to an image, you need to set the font path or use the system default:

Example

from

PIL

import

Image

,

ImageDraw

,

ImageFont

img

=

Image.

open

(

"tiger.jpeg"

)

Create a drawing object

draw

=

ImageDraw.

Draw

(

img

)

Load the font (the font must exist on the system)

font_size

=

80

 

Set the font size

try

:

    font

=

ImageFont.

truetype

(

"arial.ttf"

,

font_size

)

except

:

    font

=

ImageFont.

load_default

(

font_size

)

draw.

text

(

(

150

,

150

)

,

"Hello Runoob!"

,

fill

=

"red"

,

font

=

font

)

img.

show

(

)

The generated image is as follows:


Comprehensive Example: Create a Thumbnail and Add a Watermark

Example

from

PIL

import

Image

,

ImageDraw

,

ImageFont

def

create_thumbnail_with_watermark

(

input_path

,

output_path

,

size

=

(

200

,

200

)

)

:

   

Open the original image

    original

=

Image.

open

(

input_path

)

   

   

Create a thumbnail

    thumbnail

=

original.

copy

(

)

    thumbnail.

thumbnail

(

size

)

   

   

Add a watermark

    draw

=

ImageDraw.

Draw

(

thumbnail

)

   

try

:

        font

=

ImageFont.

truetype

(

"arial.ttf"

,

20

)

   

except

:

        font

=

ImageFont.

load_default

(

)

   

   

Calculate the text position (bottom-right), Chinese needs a font set, otherwise it will be garbled

    text

=

"WWW.RUNOOB.COM"

   

Get the text size

    bbox

=

draw.

textbbox

(

(

0

,

0

)

,

text

,

font

=

font

)

    text_width

=

bbox

[

2

]

[

0

]

    text_height

=

bbox

[

3

]

[

1

]

    x

=

thumbnail.

width

10

    y

=

thumbnail.

height

10

   

   

Draw a semi-transparent background

    draw.

rectangle

(

[

x-

5

,

y-

5

,

x+text_width+

5

,

y+text_height+

5

]

,

fill

=

(

0

,

0

,

0

,

128

)

)

   

   

Draw the text

    draw.

text

(

(

x

,

y

)

,

text

,

fill

=

"white"

,

font

=

font

)

   

   

Save the result

    thumbnail.

save

(

output_path

)

   

print

(

f

"Thumbnail saved to {output_path}"

)

Usage examples

create_thumbnail_with_watermark

(

"tiger.jpeg"

,

"thumbnail.jpg"

)

The generated thumbnail is as follows:


Frequently Asked Questions

Q1: How to handle image formats that Pillow cannot recognize?

A1: Pillow supports most common image formats. If you encounter an unsupported format, you can try installing additional decoders or first converting the image to a supported format (such as PNG or JPEG).

Q2: How to batch process multiple image files?

A2: You can use Python's glob module with a loop to batch process:

Example

import

glob

from

PIL

import

Image

for

file

in

glob

.

glob

(

"images/*.jpg"

)

:

    img

=

Image.

open

(

file

)

   

Processing image...

    img.

save

(

f

"processed_{file}"

)

Q3: How to handle large images without running out of memory?

A3: For very large images, you can use the Image object's load() method to process block by block, or use ImageOps.fit() to limit the processing area.

Through the above examples and explanations, you should have mastered the basic usage of Pillow. Pillow is powerful, it is recommended to practice more and explore its more advanced features!