How to Convert JPG to PNG and Vice-Versa using Python

To convert JPG to PNG and vice-versa in Python, you can use a pillow library’s Image.save() method.

Convert JPG to PNG Image

Step 1: Install Pillow

First, you need to install the Pillow library if you haven’t already. You can do this using pip:

python3 -m pip install pillow

# OR

pip install pillow

I used Macbook and Python3, so I used the first command.

Step 2: Import PIL Module from a pillow

from PIL import Image

Step 3: Example

The Image.open() method opens the JPG image file located at the specified path.

Then, use the Image.save() method to save the opened image in PNG format with your desired file name and path.

Visual Representation

Python Convert JPG to PNG Image

from PIL import Image

# Open the JPG image
jpg_image = Image.open('Krunal_beard.jpg')

# Save it as a PNG image
jpg_image.save('Krunal_beard.png')

print("Image has been successfully converted to PNG format.")

Output

Krunal_beard_png

Image has been successfully converted to PNG format.

Convert PNG to JPG Image

Visual RepresentationPython Convert PNG to JPG Image

Example

from PIL import Image

# Open the PNG image
png_image = Image.open('Krunal_beard.png')

# Save it as a JPG image
png_image.save('Krunal_beard_2.jpg')

print("Image has been successfully converted to JPG format.")

Output

Krunal_beard_2_jpg

Image has been successfully converted to JPG format.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.