How to Convert JPG to PNG using Python

The following syntax can be used to convert JPG to PNG using Python:

from PIL import Image

im1 = Image.open(r'path where the JPG is stored\file name.jpg')
im1.save(r'path where the PNG will be stored\new file name.png')

Next, you’ll see the full steps to apply the above syntax in practice.

Steps to Convert JPG to PNG using Python

Step 1: Install the PIL Package

If you haven’t already done so, install the PIL package using the command below:

pip install Pillow

You may check the following guide that explains how to install a package in Python under Windows.

Step 2: Capture the Path where the JPG is Stored

Next, capture the path where your JPG file is stored.

For demonstration purposes, let’s suppose that a JPG file (called ‘autumn‘) is stored under the following path:

C:\Users\Ron\Desktop\Test

Step 3: Convert the JPG to PNG using Python

Finally, you may use the syntax below in order to convert the JPG to PNG using Python:

from PIL import Image

im1 = Image.open(r'path where the JPG is stored\file name.jpg')
im1.save(r'path where the PNG will be stored\new file name.png')

For our example:

  • The path where the JPG is currently stored is: C:\Users\Ron\Desktop\Test
    • Where the file name is ‘autumn‘ and the file extension is ‘jpg
  • The path where the PNG will be stored is: C:\Users\Ron\Desktop\Test
    • Where the new file name is ‘new_autumn‘ and the file extension is ‘png

This is how the complete Python code would look like for our example (you’ll need to modify 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\autumn.jpg')
im1.save(r'C:\Users\Ron\Desktop\Test\new_autumn.png')

Run the code (adjusted to your paths), and the new PNG file will be created at your specified location.

You may also want to check the following guide that explains the steps to convert PNG to JPG using Python.