File I/O · 18 min

Read binary files and transform images

Use byte mode for binary data and Pillow to read, transform, and save a PNG.

Jump to the automation lab

Text mode decodes bytes into characters. Binary mode such as open(path, "rb") returns raw bytes instead. Use binary mode for formats such as PNG, where the file contains an encoded image.

Pillow is installed as pillow and imported as PIL. Image.open() reads the format, convert("L") makes a grayscale image, and save() writes the result. This example creates its own small input file.

Follow the example

Pillow recognizes the PNG file.

Worked examples

Save two frames as an animated GIF

Pillow writes the first frame and appends the second. A duration of 300 means each frame lasts 300 milliseconds. A loop value of zero repeats indefinitely.

blink.py
from PIL import Image

first = Image.new("RGB", (16, 16), "navy")
second = Image.new("RGB", (16, 16), "orange")
first.save("blink.gif", save_all=True, append_images=[second], duration=300, loop=0)

with Image.open("blink.gif") as animation:
    print(animation.n_frames)  # 2

Run the example and practice

Save a grayscale copy at the original size. Keep the check that reads the first eight bytes of the PNG.

Target output

L 4x2
PNG
Show a hint

Call original.convert("L") before saving it as result.png.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
from PIL import Image

Image.new("RGB", (4, 2), "steelblue").save("tile.png")

with Image.open("tile.png") as original:
    original.convert("L").save("result.png")

with Image.open("result.png") as result:
    print(f"{result.mode} {result.width}x{result.height}")

with open("result.png", "rb") as file:
    signature = file.read(8)
print("PNG" if signature.hex() == "89504e470d0a1a0a" else "Unexpected format")

Automation lab

Make thumbnails at a consistent size

Use Pillow to fit an image within a 120-pixel square while keeping its aspect ratio. The example creates a sample image.

Output

Ready

Run the example to see the output here.

Use a portrait source, then try a smaller square. Which dimension reaches the limit?

Further reading in Automate the Boring Stuff with Python by Al Sweigart