Python Image Conversion - How do I convert PNG to JPG and JPG to PNG
Published January 31, 2022JPG and PNG are two of the most used image formats. In this post, we will convert a JPG image to a PNG and a PNG to a JPG. Simply follow the instructions outlined below:
Step 1: We will first need to create a GUI interface using the Tkinter library in Python. This is the standard Python application interface. We can add Tkinter to our application by importing it using the following command
from tkinter import * |
Step 2: Now, Add the following lines to your code to import the required libraries:
|
Step 3: The libraries are successfully added to our application so let's move on to creating the functions to convert JPG to PNG and, secondly, PNG to JPG
Syntax to convert JPG to PNG
img = Image.open("Image.jpg") img.save("Image.png") |
Syntax to convert PNG to JPG
img = Image.open("Image.png") img.save("Image.jpg") |
Step 4: Copy and paste the following code
# import all Libraries from tkinter import * from tkinter import filedialog as fd import os from PIL import Image from tkinter import messagebox root = Tk() root.title("Image_Conversion_App") def jpg_to_png(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(".jpg"):
im1 = Image.open(import_filename) export_filename = fd.asksaveasfilename(defaultextension=".png") im1.save(export_filename) messagebox.showinfo("Image Conversion success") else: Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Conversion failed") def png_to_jpg(): global im1 import_filename = fd.askopenfilename() if import_filename.endswith(".png"): im1 = Image.open(import_filename) export_filename = fd.asksaveasfilename(defaultextension=".jpg") im1.save(export_filename) messagebox.showinfo("Image Conversion success ") else: Label_2 = Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) messagebox.showerror("Conversion failed") button1 = Button(root, text="JPG_to_PNG", width=18, height=2, font=("helvetica", 11), command=jpg_to_png)
button1.place(x=120, y=120)
button2 = Button(root, text="PNG_to_JPEG", width=18, height=2, font=("helvetica", 11), command=png_to_jpg)
button2.place(x=120, y=220) root.geometry("500x500+400+200") root.mainloop() |
Step 5: Run your application Now. Everything works fine, and we can convert images with JPG extensions to PNGs and vice versa
![]() |
![]() |
![]() |
Article Contributed By :
|
|
|
|
362 Views |