使用python創(chuàng)建圖片格式轉(zhuǎn)換器的實現(xiàn)步驟
在本篇博客中,我們將通過一個簡單的實例來展示如何使用 wxPython
創(chuàng)建一個圖形用戶界面(GUI)應用程序,用于將圖片從一種格式轉(zhuǎn)換為另一種格式。我們將通過以下幾個步驟實現(xiàn)這一目標:
C:\pythoncode\new\imageconverttype.py
- 選擇多個
.png
文件。 - 選擇目標文件類型(例如,
jpeg
,gif
,png
,bmp
,webp
)。 - 點擊“轉(zhuǎn)換”按鈕,將選擇的文件轉(zhuǎn)換為目標格式。
- 將轉(zhuǎn)換后的文件保存到指定的文件夾中。
全部代碼
import wx import os from PIL import Image class ImageConverter(wx.Frame): def __init__(self, *args, **kw): super(ImageConverter, self).__init__(*args, **kw) self.InitUI() def InitUI(self): panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) # 選擇文件按鈕 self.files_button = wx.Button(panel, label="選擇圖片文件") self.files_button.Bind(wx.EVT_BUTTON, self.on_select_files) # 顯示選擇的文件列表 self.files_list = wx.ListBox(panel, size=(400, 150)) # 選擇轉(zhuǎn)換后的文件類型 self.target_format_choice = wx.Choice(panel, choices=["JPEG", "GIF", "PNG", "BMP", "WEBP"]) self.target_format_choice.SetSelection(0) # 默認選擇JPEG # 選擇保存的文件夾 self.output_folder_button = wx.Button(panel, label="選擇保存文件夾") self.output_folder_button.Bind(wx.EVT_BUTTON, self.on_select_folder) # 顯示選中的保存文件夾路徑 self.output_folder_text = wx.TextCtrl(panel, size=(400, 25), style=wx.TE_READONLY) # 轉(zhuǎn)換按鈕 self.convert_button = wx.Button(panel, label="轉(zhuǎn)換") self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert) # 布局 vbox.Add(self.files_button, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.files_list, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.target_format_choice, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.output_folder_button, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.output_folder_text, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.convert_button, flag=wx.EXPAND | wx.ALL, border=10) panel.SetSizer(vbox) self.SetSize((500, 400)) self.SetTitle('圖片格式轉(zhuǎn)換器') self.Centre() self.Show(True) def on_select_files(self, event): with wx.FileDialog(self, "選擇圖片文件", wildcard="PNG files (*.png)|*.png", style=wx.FD_OPEN | wx.FD_MULTIPLE) as dlg: if dlg.ShowModal() == wx.ID_OK: paths = dlg.GetPaths() self.files_list.SetItems(paths) def on_select_folder(self, event): with wx.DirDialog(self, "選擇保存文件夾", style=wx.DD_DEFAULT_STYLE) as dlg: if dlg.ShowModal() == wx.ID_OK: self.output_folder_text.SetValue(dlg.GetPath()) def on_convert(self, event): # 獲取選擇的文件路徑和目標格式 selected_files = self.files_list.GetStrings() target_format = self.target_format_choice.GetStringSelection().lower() output_folder = self.output_folder_text.GetValue() if not selected_files or not output_folder: wx.MessageBox("請選擇文件和目標文件夾", "錯誤", wx.ICON_ERROR) return if target_format not in ["jpeg", "gif", "png", "bmp", "webp"]: wx.MessageBox("無效的目標格式", "錯誤", wx.ICON_ERROR) return # 轉(zhuǎn)換每個文件 for file in selected_files: try: # 打開圖片 with Image.open(file) as img: # 確定輸出文件名 base_name = os.path.splitext(os.path.basename(file))[0] output_path = os.path.join(output_folder, f"{base_name}.{target_format}") # 保存為目標格式 img.convert("RGB").save(output_path, target_format.upper()) wx.MessageBox(f"轉(zhuǎn)換成功: {output_path}", "完成", wx.ICON_INFORMATION) except Exception as e: wx.MessageBox(f"轉(zhuǎn)換失敗: {file}\n錯誤: {str(e)}", "錯誤", wx.ICON_ERROR) if __name__ == '__main__': app = wx.App(False) ImageConverter(None) app.MainLoop()
準備工作
首先,確保你已經(jīng)安裝了 wxPython
和 Pillow
(Python Imaging Library)。這兩個庫將分別用于創(chuàng)建界面和處理圖片轉(zhuǎn)換功能。
在命令行中使用 pip
安裝:
pip install wxPython Pillow
wxPython
:用于創(chuàng)建跨平臺的桌面應用程序。Pillow
:用于處理圖像文件,如打開、轉(zhuǎn)換格式、保存等。
代碼實現(xiàn)
接下來,我們將通過代碼實現(xiàn)上述功能。
import wx import os from PIL import Image class ImageConverter(wx.Frame): def __init__(self, *args, **kw): super(ImageConverter, self).__init__(*args, **kw) self.InitUI() def InitUI(self): panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) # 選擇文件按鈕 self.files_button = wx.Button(panel, label="選擇圖片文件") self.files_button.Bind(wx.EVT_BUTTON, self.on_select_files) # 顯示選擇的文件列表 self.files_list = wx.ListBox(panel, size=(400, 150)) # 選擇轉(zhuǎn)換后的文件類型 self.target_format_choice = wx.Choice(panel, choices=["JPEG", "GIF", "PNG", "BMP", "WEBP"]) self.target_format_choice.SetSelection(0) # 默認選擇JPEG # 選擇保存的文件夾 self.output_folder_button = wx.Button(panel, label="選擇保存文件夾") self.output_folder_button.Bind(wx.EVT_BUTTON, self.on_select_folder) # 顯示選中的保存文件夾路徑 self.output_folder_text = wx.TextCtrl(panel, size=(400, 25), style=wx.TE_READONLY) # 轉(zhuǎn)換按鈕 self.convert_button = wx.Button(panel, label="轉(zhuǎn)換") self.convert_button.Bind(wx.EVT_BUTTON, self.on_convert) # 布局 vbox.Add(self.files_button, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.files_list, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.target_format_choice, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.output_folder_button, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.output_folder_text, flag=wx.EXPAND | wx.ALL, border=10) vbox.Add(self.convert_button, flag=wx.EXPAND | wx.ALL, border=10) panel.SetSizer(vbox) self.SetSize((500, 400)) self.SetTitle('圖片格式轉(zhuǎn)換器') self.Centre() self.Show(True) def on_select_files(self, event): with wx.FileDialog(self, "選擇圖片文件", wildcard="PNG files (*.png)|*.png", style=wx.FD_OPEN | wx.FD_MULTIPLE) as dlg: if dlg.ShowModal() == wx.ID_OK: paths = dlg.GetPaths() self.files_list.SetItems(paths) def on_select_folder(self, event): with wx.DirDialog(self, "選擇保存文件夾", style=wx.DD_DEFAULT_STYLE) as dlg: if dlg.ShowModal() == wx.ID_OK: self.output_folder_text.SetValue(dlg.GetPath()) def on_convert(self, event): # 獲取選擇的文件路徑和目標格式 selected_files = self.files_list.GetStrings() target_format = self.target_format_choice.GetStringSelection().lower() output_folder = self.output_folder_text.GetValue() if not selected_files or not output_folder: wx.MessageBox("請選擇文件和目標文件夾", "錯誤", wx.ICON_ERROR) return if target_format not in ["jpeg", "gif", "png", "bmp", "webp"]: wx.MessageBox("無效的目標格式", "錯誤", wx.ICON_ERROR) return # 轉(zhuǎn)換每個文件 for file in selected_files: try: # 打開圖片 with Image.open(file) as img: # 確定輸出文件名 base_name = os.path.splitext(os.path.basename(file))[0] output_path = os.path.join(output_folder, f"{base_name}.{target_format}") # 保存為目標格式 img.convert("RGB").save(output_path, target_format.upper()) wx.MessageBox(f"轉(zhuǎn)換成功: {output_path}", "完成", wx.ICON_INFORMATION) except Exception as e: wx.MessageBox(f"轉(zhuǎn)換失敗: {file}\n錯誤: {str(e)}", "錯誤", wx.ICON_ERROR) if __name__ == '__main__': app = wx.App(False) ImageConverter(None) app.MainLoop()
代碼解析
界面設計:使用
wx.Panel
和wx.BoxSizer
來構(gòu)建應用的布局。- 選擇文件按鈕:通過
wx.FileDialog
讓用戶選擇多個.png
文件。 - 目標文件類型選擇:使用
wx.Choice
讓用戶選擇目標格式(如 JPEG, GIF, PNG, BMP, WEBP)。 - 保存文件夾選擇:通過
wx.DirDialog
讓用戶選擇一個文件夾來保存轉(zhuǎn)換后的文件。 - 轉(zhuǎn)換按鈕:點擊按鈕后,將所選文件轉(zhuǎn)換并保存到指定文件夾。
- 選擇文件按鈕:通過
圖片轉(zhuǎn)換:使用
Pillow
庫來處理圖片的轉(zhuǎn)換。我們通過Image.open()
打開圖片,調(diào)用convert("RGB")
方法以確保圖像可以轉(zhuǎn)換為目標格式,然后調(diào)用save()
保存為新的格式。錯誤處理:如果文件轉(zhuǎn)換失敗或用戶未選擇文件、文件夾等,程序會彈出錯誤消息框,提示用戶。
運行和測試
- 啟動程序后,點擊 “選擇圖片文件” 按鈕,選擇要轉(zhuǎn)換的
.png
文件。 - 選擇目標格式(如
jpeg
,gif
,bmp
等)。 - 點擊 “選擇保存文件夾” 按鈕,選擇保存文件的目錄。
- 最后,點擊 “轉(zhuǎn)換” 按鈕,程序會將選擇的圖片轉(zhuǎn)換為目標格式,并保存在指定文件夾中。
結(jié)果如下
到此這篇關(guān)于使用python創(chuàng)建圖片格式轉(zhuǎn)換器的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)python圖片格式轉(zhuǎn)換器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python串口實時顯示數(shù)據(jù)并繪圖的例子
今天小編就為大家分享一篇使用Python串口實時顯示數(shù)據(jù)并繪圖的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12解決pyinstaller打包發(fā)布后的exe文件打開控制臺閃退的問題
今天小編就為大家分享一篇解決pyinstaller打包發(fā)布后的exe文件打開控制臺閃退的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06利用django model save方法對未更改的字段依然進行了保存
這篇文章主要介紹了利用django model save方法對未更改的字段依然進行了保存,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03python實現(xiàn)網(wǎng)頁鏈接提取的方法分享
這篇文章主要介紹了python實現(xiàn)的網(wǎng)頁鏈接提取的方法,需要的朋友可以參考下2014-02-02python 實現(xiàn)二維數(shù)組的索引、刪除、拼接操作
這篇文章主要介紹了python 實現(xiàn)二維數(shù)組的索引、刪除、拼接操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05解決安裝tensorflow遇到無法卸載numpy 1.8.0rc1的問題
今天小編就為大家分享一篇解決安裝tensorflow遇到無法卸載numpy 1.8.0rc1的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06