0
0
PythonHow-ToBeginner · 3 min read

How to Save Image in Python: Simple Guide with Examples

To save an image in Python, use the Pillow library's Image.save() method after loading or creating an image object. This method writes the image to a file in the desired format like PNG or JPEG.
📐

Syntax

The basic syntax to save an image using Pillow is:

  • Image.save(filename, format=None)

Here, filename is the path where you want to save the image, and format is optional (e.g., 'PNG', 'JPEG'). If format is not provided, Pillow guesses it from the file extension.

python
from PIL import Image

# image is an Image object
image.save('path/to/image.png', format='PNG')
💻

Example

This example opens an existing image file and saves a copy with a new name and format.

python
from PIL import Image

# Open an existing image
image = Image.open('example.jpg')

# Save the image as PNG
image.save('example_copy.png', format='PNG')

print('Image saved successfully.')
Output
Image saved successfully.
⚠️

Common Pitfalls

Common mistakes when saving images include:

  • Not installing the Pillow library (pip install Pillow needed).
  • Using incorrect file paths or missing file extensions.
  • Forgetting to specify the format when the file extension is missing or ambiguous.
  • Trying to save images without opening or creating them first.
python
from PIL import Image

# Wrong: saving without opening or creating an image
# image = None
# image.save('output.png')  # This will cause an error

# Right way:
image = Image.new('RGB', (100, 100), color='red')
image.save('output.png')
📊

Quick Reference

Summary tips for saving images in Python:

  • Use Pillow library for easy image saving.
  • Call Image.save() with a valid filename.
  • Specify format if file extension is missing or unclear.
  • Ensure the image object is valid before saving.

Key Takeaways

Use Pillow's Image.save() method to save images in Python.
Always provide a valid filename with an extension or specify the format explicitly.
Make sure the image object is properly loaded or created before saving.
Install Pillow library using pip if not already installed.
Check file paths carefully to avoid errors when saving images.