Python Pillow - Save image as PNG


Python Pillow - Save image as PNG

You can save an image in PNG format with .png file extension using Pillow library in Python.

PNG format is generally used for the images that require transparent or semitransparent backgrounds.

To save an Image object in PNG format using Pillow, call Image.save() method on the Image object, and specify 'PNG' for format parameter.

A quick code snippet to save an Image object image in PNG format would be as shown in the following.

image.save('output_image.png', format='PNG')

Let us go through some examples.

We shall use the below image as input image in the following examples.

Python Pillow - Save image as PNG
input_image.jpg

1. Save Image as PNG using Image.save() in Pillow

In this example, we shall read an input image using Image.open() into a variable image. Then, we shall save this image as a PNG image using Image.save().

Since this example is for only demonstrating how to save an image as a PNG image, we are neither modifying the image not applying any transformations on it. But, in realtime applications, you might be doing additional operations on the image. Or, if you are just converting your images into PNG format, then this is a perfect example.

Python Program

from PIL import Image

# Open the input image
image = Image.open('input_image.jpg')

# Save the image as a PNG file
image.save('output_image.png', format='PNG')

# Close the image
image.close()

output_image.png

Python Pillow - Save image as PNG - Output image
Saved PNG image

We mentioned that PNG supports transparency channel (or alpha channel) and generally occupies more storage space than a JPG image.

File size in disk

Comparing size between JPG and PNG

The numbers are out there. The input image is of size 41KB, while the PNG formatted image is 208KB.

Summary

In this Python Pillow tutorial, we learned how to save an image in PNG format using Pillow library in Python, with examples. We have taken an input image and saved the image in PNG format using Image.save() method from Pillow library.