Skip to content

How to Fix Python Pillow Image Save Error

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Python Pillow Image Save Error. We cover key concepts, practical examples, and best practices.

Pillow raises KeyError or OSError when saving images if the file extension is not recognized, the image mode is incompatible with the format, or the path is invalid.

The Wrong Way

from PIL import Image

img = Image.new("RGBA", (100, 100), (255, 0, 0))
img.save("image.jpg")

Output:

OSError: cannot write mode RGBA as JPEG

The Right Way

from PIL import Image

img = Image.new("RGBA", (100, 100), (255, 0, 0))

# Convert to RGB for JPEG
if img.mode == "RGBA":
    img = img.convert("RGB")

img.save("image.jpg", quality=85, optimize=True)
print("Saved as JPEG")

# Or save as PNG (supports RGBA)
img_rgba = Image.new("RGBA", (100, 100), (255, 0, 0, 128))
img_rgba.save("image.png")
print("Saved as PNG")

Output:

Saved as JPEG
Saved as PNG

Prevention Tips

  • Check img.mode before saving and convert if needed.
  • Use JPEG for photos, PNG for graphics with transparency.
  • Use optimize=True and quality=85 for JPEG.
  • Use format parameter to override extension detection.
  • Create output directories before saving.

Common Mistakes with pillow image save

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What image modes does Pillow support?

Pillow supports 1 (binary), L (grayscale), P (palette), RGB, RGBA, CMYK, YCbCr, I (integer), and F (float). Each mode has format compatibility. Use img.convert() to change modes.

Why does Pillow save an all-black image?

The image was created but not drawn on. Fill it with ImageDraw.Draw(img).rectangle() or load pixel data. Use img.show() to preview before saving.

How do I save images with metadata?

Pass exif=exif_data to img.save() for JPEG EXIF data. Use img.info to view current metadata. Some formats preserve metadata, others do not.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro