In this post, we will learn how to convert JPG to PNG in Python with detailed explanations and examples. So letβs get started.
You can also checkout this post π Remove Background From Images in Python
To convert JPG to PNG, first, we need to install the Python Pillow library. Pillow is an external Python library that allows us to change the extension of our images. To install it, run the command below in your terminal.
pip install pillow
After Installation is done, you need to follow the following steps to convert the JPG image to PNG.
Steps to Convert JPG to PNG
- Import image module from pillow library.
from PIL import Image
.
- Open your JPG image using the
open()
function from theImage
module of the Pillow library and save it in variable calledimg
.img = Image.open(path/filename.jpg)
- After opening your JPG image, use the
save()
method to save it with a PNG extension.img.save(path/filename.png)
After completing the above three steps your JPG image has been successfully converted to PNG.
Source Code
from PIL import Image
img = Image.open("dog.jpg")
img.save("dog1.png")
print("Successfully Converted (JPG --> PNG)")
Output
Successfully Converted (JPG --> PNG)
NOTE: Both my source code file and the image are located in the same directory, so I only need to write the name of the file. If your image file is located in any other place, you have to mention the absolute path of your image.
Similarly, you can change your JPG image to WEBP image. Here is the Source Code.
Convert JPG to WEBP
from PIL import Image
img = Image.open("dog.jpg")
img.save("dog.webp")
print("Successfully Converted (JPG --> WEBP)")
Output
Successfully Converted (JPG --> WEBP)