PIL
module) demonstrations¶David Dumas
import PIL
# Let's open a JPEG photo
# This is a resized version of the photo from https://unsplash.com/photos/iHOZTi2niV4
# which is licensed for use without attribution, and allows modification.
img = PIL.Image.open("pillow-photo.jpg")
img
# To grayscale
# Note: .convert returns a new image
img_gray = img.convert("L")
img_gray.save("pillow-photo-gray.png") # Write grayscale version to a PNG file
img_gray
# To black and white (1-bit)
img_bw = img.convert("1",dither=PIL.Image.NONE)
img_bw
# To black and white (1-bit)
# Without passing `dither=PIL.Image.NONE`, it uses patterned black/white pixels
# to give the impression of shades of gray. This is called dithering.
# Your browser may resize the image a bit (making it smaller) resulting in some
# *actual* gray pixels being shown.
img_bw = img.convert("1")
img_bw
# crop returns a new image
img_portion = img.crop( (85,52,245,200) ) # 4-tuple is (left_x, top_y, right_x, bottom_y)
img_portion
# Check the size of the cropped portion
w,h = img_portion.size
w,h
# Resize returns a new image; it isn't a mutation!
w,h = img_portion.size
img_portion.resize( (3*w,int(1.5*h)) ) # (new width, new height)
# This is 3 times as wide, 1.5 times as tall
# Dimensions must be integers