楔子
平時使用Snipaste截圖總是不注意圖片的尺寸,導致保存了一堆大大小小尺寸不一的圖片
在寫文檔的時候插入圖片顯得很雜亂,因此抽空寫了個小工具幫我批量格式化文件夾中的圖片尺寸成一樣的大小
代碼
import os
from tkinter import *
class Application(object):
def __init__(self):
self.root = Tk()
self.root.title('格式化圖片尺寸')
self.path = StringVar()
self.size = StringVar()
Label(self.root, text="目標路徑:").grid(row=0, column=0)
Entry(self.root, textvariable=self.path).grid(row=0, column=1)
Button(self.root, text="路徑選擇", command=self.selectPath).grid(row=0, column=2)
Label(self.root, text="目標大小:").grid(row=1, column=0)
Entry(self.root, textvariable=self.size).grid(row=1, column=1)
Button(self.root, text="確定選擇", command=self.formatSize).grid(row=1, column=2)
Button(self.root, text="退出程序", command=self.root.destroy).grid(row=2, column=2)
def run(self):
self.root.mainloop()
def selectPath(self):
from tkinter.filedialog import askdirectory
path_ = askdirectory()
self.path.set(path_)
def formatSize(self):
from PIL import Image
from glob import glob
import tkinter.messagebox as messagebox
sourcesPathList = glob(os.path.join(self.path.get(), '*.png'))
sourcesPathList.extend(glob(os.path.join(self.path.get(), '*.jpg')))
sourcesPathList.extend(glob(os.path.join(self.path.get(), '*.jpeg')))
sourcesPathList.extend(glob(os.path.join(self.path.get(), '*.bmp')))
if not os.path.exists('./result'):
os.mkdir('./result')
try:
if not sourcesPathList:
messagebox.showinfo('警告', '所選文件夾內容為空')
assert not '0'
for p in sourcesPathList:
tmp = Image.open(p)
try:
res = tmp.resize([int(i) for i in self.size.get().split(',')], Image.ANTIALIAS)
except ValueError:
res = tmp.resize([int(i) for i in self.size.get().split(',')], Image.ANTIALIAS)
res.save(os.path.join('./result', p.split('\\')[-1]), quality=95)
messagebox.showinfo('提示', '修改成功')
except (FileNotFoundError, AssertionError):
messagebox.showinfo('警告', '修改失敗')
if __name__ == '__main__':
app = Application()
app.run()
使用說明
1、命令行 python formatPic.py
2、
3、點擊路徑選擇(只需要選擇圖片文件所在的文件夾,推薦把要修改尺寸的圖片都放到一個文件夾下)
4、輸入目標大小(100,200或者100,200,可以兼容中英文標點)
5、點擊確定選擇
6、修改成功或失敗皆會有彈窗提示
7、使用完畢點擊退出程序即可關閉
8、修改好尺寸的圖片可以到腳本同路徑下的 result
文件夾下查看
【完】