使用Python将文件从 jpg 转换为 png,反之亦然
先决条件:枕头图书馆
有时需要在我们需要具有指定扩展名的图像文件的位置附加图像。我们有不同扩展名的图像,需要使用指定的扩展名进行转换,像这样我们将具有PNG 扩展名的图像转换为 JPG ,反之亦然
此外,我们将创建代码的GUI 界面,因此我们将需要库tkinter Tkinter是到Tk GUI 工具包的Python绑定。它是 Tk GUI 工具包的标准Python接口,也是 Python 的事实上的标准 GUI。
请按照以下步骤操作:
第 1 步:导入库。
from PIL import Image
第 2 步: JPG 转 PNG
To convert the image From JPG to PNG : {Syntax}
img = Image.open("Image.jpg")
img.save("Image.png")
第 3 步: PNG → JPG
To convert the Image From PNG to JPG
img = Image.open("Image.png")
img.save("Image.jpg")
添加GUI界面
from tkinter import *
方法:
- 在函数jpg_to_png 中,我们首先检查选择的图像是否与要转换为 .jpg 的格式相同( .jpg) 。 png如果不是,则返回错误。
- 否则将图像转换为.png
- 要打开图像,我们使用 tkinter 中名为FileDialog的函数,它有助于从文件夹中打开图像
从 tkinter 导入文件对话框作为 fd - PNG 到 JPG 的相同方法
下面是实现:
Python3
# import all prerequisite
from tkinter import *
from tkinter import filedialog as fd
import os
from PIL import Image
from tkinter import messagebox
root = Tk()
# naming the GUI interface to image_conversion_APP
root.title("Image_Conversion_App")
# creating the Function which converts the jpg_to_png
def jpg_to_png():
global im1
# import the image from the folder
import_filename = fd.askopenfilename()
if import_filename.endswith(".jpg"):
im1 = Image.open(import_filename)
# after converting the image save to desired
# location with the Extersion .png
export_filename = fd.asksaveasfilename(defaultextension=".png")
im1.save(export_filename)
# displaying the Messaging box with the Success
messagebox.showinfo("success ", "your Image converted to Png")
else:
# if Image select is not with the Format of .jpg
# then display the Error
Label_2 = Label(root, text="Error!", width=20,
fg="red", font=("bold", 15))
Label_2.place(x=80, y=280)
messagebox.showerror("Fail!!", "Something Went Wrong...")
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("success ", "your Image converted to jpg ")
else:
Label_2 = Label(root, text="Error!", width=20,
fg="red", font=("bold", 15))
Label_2.place(x=80, y=280)
messagebox.showerror("Fail!!", "Something Went Wrong...")
button1 = Button(root, text="JPG_to_PNG", width=20, height=2, bg="green",
fg="white", font=("helvetica", 12, "bold"), command=jpg_to_png)
button1.place(x=120, y=120)
button2 = Button(root, text="PNG_to_JPEG", width=20, height=2, bg="green",
fg="white", font=("helvetica", 12, "bold"), command=png_to_jpg)
button2.place(x=120, y=220)
root.geometry("500x500+400+200")
root.mainloop()
输出: