You may use the following technique to convert PNG to JPG using Python:
from PIL import Image im1 = Image.open(r'path where the PNG is stored\file name.png') im1.save(r'path where the JPG will be stored\new file name.jpg')
Next, you’ll see the complete steps to convert PNG to JPG using a simple example.
Steps to Convert PNG to JPG using Python
Step 1: Install the PIL package
You can install the PIL package using the command below (under Windows):
pip install Pillow
You may wish to refer to the following guide for the steps to install a Python package under Windows.
Step 2: Capture the path where the PNG is stored
Next, capture the path where the PNG file is stored on your computer.
For example, let’s suppose that a PNG file (called ‘summer‘) is stored under the following path:
C:\Users\Ron\Desktop\Test
Step 3: Convert the PNG to JPG using Python
Finally, you may use the template below in order to convert your PNG to JPG:
from PIL import Image im1 = Image.open(r'path where the PNG is stored\file name.png') im1.save(r'path where the JPG will be stored\new file name.jpg')
For our example:
- The path where the PNG is currently stored is: C:\Users\Ron\Desktop\Test
- Where the file name is ‘summer’ and the file extension is ‘png’
- The path where the JPG will be stored is: C:\Users\Ron\Desktop\Test
- Where the new file name is ‘new_summer’ and the file extension is ‘jpg’
This is the complete Python code to convert the PNG to JPG for our example (make sure to adjust the paths to reflect the location where the files will be stored on your computer):
from PIL import Image im1 = Image.open(r'C:\Users\Ron\Desktop\Test\summer.png') im1.save(r'C:\Users\Ron\Desktop\Test\new_summer.jpg')
Run the code (adjusted to your paths), and you’ll get the new JPG file at your specified location.
Alternatively, you may wish to check the following guide that explains how to convert JPG to PNG using Python.