Convert JPG to PNG using Python

In this tutorial, I am going to convert a .jpg Image into a .png Image using Python. JPG and PNG are raster image file types. JPGs are used to store digital images and PNGs are used to store illustrations, logos, charts, etc.

Requirement


  • OpenCV
  • PIL

To get started make sure you have OpenCV and PIL (Python Image Library) installed in your system. If you don’t have these you have to install them using PIP which is a package manager for Python that can install Python modules or packages.

Using these following commands you can install OpenCV and PIL in your system

pip install opencv-python
pip install Pillow

Method 1

Using OpenCV:

OpenCV is an Image-Processing library in Python that provides various functions to manipulate image files. In this method I am going to use imread() which will open the image file and imwrite() function which will modify the image

Code:
import cv2 
  
# Loading the .jpg image 
img = cv2.imread('plane.jpg') 
  
# Converting & Saving to PNG
cv2.imwrite('plane.png', img)

Method 2

Using PIL:

In this method, I am going to use Image.open() function that opens the image file and img.save() function saves the image with the specified file name and extension.

Code:
from PIL import Image

#Loading the .jpg image
img = Image.open("plane.jpg")

#Converting & Saving to PNG
img.save("plane.png")

Output

Before:

After:

After executing the code .png file of the provided image is generated.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top