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
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
Image has been successfully converted to PNG format.
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
Image has been successfully converted to JPG format.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.