前言
直接上代码了哈
一、使用步骤
1.引入库
代码如下(示例):
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter.filedialog import *
from PIL import Image, ImageTk
import os
from datetime import datetime
# from wand.image import Image
2.主代码
代码如下(示例):
# 定义全局变量
image_list = []
choose_radio_value = 'jpg'
"""
askopenfilename函数:打开文件对话框,用于选择一个文件,返回文件路径,类型为字符串
askopenfilenames函数:打开文件对话框,用于选择多个文件,返回一个元组,包括所有选择文件的路径
"""
# 打开特定目录
def open_directory():
current_folder = os.getcwd() # 获取当前文件夹(作为默认文件夹)
current_folder = f"{current_folder}\\data"
save_file_directory = current_folder # 文件保存目录 (如果不存在则使用默认目录)
if not os.path.exists(save_file_directory):
os.makedirs(save_file_directory)
save_dir = os.path.dirname(f"{save_file_directory}/")
# print(save_dir)
os.system('start ' + save_dir)
def create_image_label(frame2, img_path, row, column):
img = Image.open(img_path)
img = img.resize((100, 100), Image.Resampling.LANCZOS) # 假设我们要显示的图片大小为100x100
photo = ImageTk.PhotoImage(img)
label = Label(frame2, image=photo)
label.image = photo # 防止图片被垃圾回收
label.grid(row=row, column=column)
def upload_images():
global image_list
# 读取图片打开图片
filetypes = [
('All files', '*'),
('JPG files', '*.jpg'),
('PNG files', '*.png'),
]
image_list = askopenfilenames(title='Open an image file', filetypes=filetypes)
file_num = len(image_list)
if file_num > 20:
messagebox.showinfo('提示', '一次性最多转化20张哦!')
return False
if image_list:
clear_image() # 若重新选择了东西则,清空控件
# 初始化行和列索引
row, column = 0, 0
for img_path in image_list:
create_image_label(frame2, img_path, row, column)
column += 1
# 当列索引超过最大列数时,进行换行,并重置列索引
if column >= 10: # 假设最大列数为10,需要你根据实际情况调整
row += 1
column = 0
def clear_image():
# 遍历删除Frame内的所有控件
for widget in frame2.winfo_children():
widget.destroy()
def on_radio_click():
global choose_radio_value
choose_radio_value = radio_value.get()
# pass
# print("Selected:", radio_value.get())
# 获取文件格式
def get_format(filename):
file_format = filename.split(".")[-1]
return file_format
# python 获取随机10位数字字符串作为文件名
def generate_random_filename(length=10):
digits = [str(i) for i in range(10)]
random_digits = ''.join(random.choices(digits, k=length))
return random_digits
# 转jpg
def convert_to_jpg(image_path, jpg_image_path):
with Image.open(image_path) as image:
image.convert('RGB').save(jpg_image_path, 'JPEG', quality=100)
# 转png
def convert_to_png(image_path, png_image_path):
with Image.open(image_path) as image:
image.convert('RGB').save(png_image_path, 'PNG', quality=100)
def convert_to_bmp(image_path, bmp_image_path):
with Image.open(image_path) as image:
image.convert('RGB').save(bmp_image_path, 'BMP', quality=100)
def convert_to_tif(image_path, tif_image_path):
with Image.open(image_path) as image:
image.convert('RGB').save(tif_image_path, 'TIFF', quality=100)
# 在Python中,可以使用wand库将图片转换为EMF格式。首先需要安装wand库:pip install Wand
# 本地电脑还需要安装 ImageMagick 软件
# def convert_to_emf(image_path, emf_image_path):
# with Image.open(image_path) as img:
# img.format = 'emf'
# img.save(emf_image_path)
def convert_to_ico(image_path, ico_image_path):
with Image.open(image_path) as image:
image.convert('RGB').save(ico_image_path, format="ICO")
# 开始转换
def change_format():
# 从之前定义的全局变量中获取图片列表值
global image_list
global choose_radio_value
if len(image_list) == 0:
messagebox.showinfo('提示', '请先选择图片!')
# print(image_list)
# print(choose_radio_value)
for item in image_list:
# print(get_format(item))
transform_format = choose_radio_value # 需要转化的格式
# print(transform_format)
match transform_format:
case 'jpg':
convert_to_jpg(item, f'./data/{generate_random_filename()}.jpg')
case 'png':
convert_to_png(item, f'./data/{generate_random_filename()}.png')
case 'bmp':
convert_to_bmp(item, f'./data/{generate_random_filename()}.bmp')
case 'tif':
convert_to_tif(item, f'./data/{generate_random_filename()}.tif')
case 'ico':
convert_to_ico(item, f'./data/{generate_random_filename()}.ico')
messagebox.showinfo('提示', '转化完成!')
root = Tk()
root.title('图片格式批量转化')
root.geometry('1060x650+500+300')
frame = Frame(root, pady=10)
frame.pack()
# 上传图片
upload_button = Button(frame, text="上传图片(可多选)", command=upload_images)
upload_button.grid(row=0, column=0, columnspan=10)
# 新创建一个frame2 (更换图片时可以删除里面的所有控件)
frame2 = Frame(root, pady=10, bg='white')
frame2.pack(fill=BOTH, expand=True, padx=10)
# 新创建一个frame3 (用于存放所有格式选项)
frame3 = Frame(root, pady=10)
frame3.pack(fill=BOTH, expand=True)
# 定义一个元祖数据
img_format = [
("JPG", "jpg"),
("BMP", "bmp"),
("PNG", "png"),
("TIF", "tif"),
# ("emf", "emf"),
# ("wmf", "wmf"),
("ICO", "ico"),
]
format_label = Label(frame3, text='转化格式:', width=10, bg='white')
format_label.grid(row=0, column=0, padx=5, pady=5)
radio_value = StringVar()
radio_value.set('jpg') # 默认选择
# index = 1 # 造一个自增键
# 初始化行和列索引
Radio_row, Radio_column = 0, 1
for value, data_id in img_format: # 解构
b = Radiobutton(frame3, text=value, variable=radio_value, value=data_id, command=on_radio_click, font=("微软雅黑", 15))
b.grid(row=Radio_row, column=Radio_column, padx=(20, 0), pady=5)
Radio_column += 1
# 当列索引超过最大列数时,进行换行,并重置列索引
if Radio_column >= 8: # 假设最大列数为8,需要你根据实际情况调整
Radio_row += 1
Radio_column = 1
frame4 = Frame(root, pady=10)
frame4.pack()
transform_button = Button(frame4, text="开始转换", command=change_format)
transform_button.grid(row=0, column=0, padx=(0, 100))
directory_button = Button(frame4, text="打开目录", command=open_directory)
directory_button.grid(row=0, column=1)
root.mainloop()