欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用python創(chuàng)建圖片格式轉(zhuǎn)換器的實(shí)現(xiàn)步驟

 更新時(shí)間:2024年12月26日 08:51:12   作者:winfredzhang  
本教程將指導(dǎo)如何使用 Python 編寫(xiě)的圖片格式轉(zhuǎn)換工具 ImaCon_ter.py,該工具能夠?qū)D片從一種格式轉(zhuǎn)換為另一種格式,文章通過(guò)代碼示例講解的非常詳細(xì),感興趣的小伙伴跟著小編一起來(lái)看看吧

在本篇博客中,我們將通過(guò)一個(gè)簡(jiǎn)單的實(shí)例來(lái)展示如何使用 wxPython 創(chuàng)建一個(gè)圖形用戶界面(GUI)應(yīng)用程序,用于將圖片從一種格式轉(zhuǎn)換為另一種格式。我們將通過(guò)以下幾個(gè)步驟實(shí)現(xiàn)這一目標(biāo):
C:\pythoncode\new\imageconverttype.py

  1. 選擇多個(gè) .png 文件。
  2. 選擇目標(biāo)文件類型(例如,jpeggifpngbmpwebp)。
  3. 點(diǎn)擊“轉(zhuǎn)換”按鈕,將選擇的文件轉(zhuǎn)換為目標(biāo)格式。
  4. 將轉(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)  # 默認(rèn)選擇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):
        # 獲取選擇的文件路徑和目標(biāo)格式
        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("請(qǐng)選擇文件和目標(biāo)文件夾", "錯(cuò)誤", wx.ICON_ERROR)
            return

        if target_format not in ["jpeg", "gif", "png", "bmp", "webp"]:
            wx.MessageBox("無(wú)效的目標(biāo)格式", "錯(cuò)誤", wx.ICON_ERROR)
            return

        # 轉(zhuǎn)換每個(gè)文件
        for file in selected_files:
            try:
                # 打開(kāi)圖片
                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}")

                    # 保存為目標(biāo)格式
                    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錯(cuò)誤: {str(e)}", "錯(cuò)誤", wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App(False)
    ImageConverter(None)
    app.MainLoop()

準(zhǔn)備工作

首先,確保你已經(jīng)安裝了 wxPython 和 Pillow(Python Imaging Library)。這兩個(gè)庫(kù)將分別用于創(chuàng)建界面和處理圖片轉(zhuǎn)換功能。

在命令行中使用 pip 安裝:

pip install wxPython Pillow
  • wxPython:用于創(chuàng)建跨平臺(tái)的桌面應(yīng)用程序。
  • Pillow:用于處理圖像文件,如打開(kāi)、轉(zhuǎn)換格式、保存等。

代碼實(shí)現(xiàn)

接下來(lái),我們將通過(guò)代碼實(shí)現(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)  # 默認(rèn)選擇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):
        # 獲取選擇的文件路徑和目標(biāo)格式
        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("請(qǐng)選擇文件和目標(biāo)文件夾", "錯(cuò)誤", wx.ICON_ERROR)
            return

        if target_format not in ["jpeg", "gif", "png", "bmp", "webp"]:
            wx.MessageBox("無(wú)效的目標(biāo)格式", "錯(cuò)誤", wx.ICON_ERROR)
            return

        # 轉(zhuǎn)換每個(gè)文件
        for file in selected_files:
            try:
                # 打開(kāi)圖片
                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}")

                    # 保存為目標(biāo)格式
                    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錯(cuò)誤: {str(e)}", "錯(cuò)誤", wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App(False)
    ImageConverter(None)
    app.MainLoop()

代碼解析

  1. 界面設(shè)計(jì):使用 wx.Panel 和 wx.BoxSizer 來(lái)構(gòu)建應(yīng)用的布局。

    • 選擇文件按鈕:通過(guò) wx.FileDialog 讓用戶選擇多個(gè) .png 文件。
    • 目標(biāo)文件類型選擇:使用 wx.Choice 讓用戶選擇目標(biāo)格式(如 JPEG, GIF, PNG, BMP, WEBP)。
    • 保存文件夾選擇:通過(guò) wx.DirDialog 讓用戶選擇一個(gè)文件夾來(lái)保存轉(zhuǎn)換后的文件。
    • 轉(zhuǎn)換按鈕:點(diǎn)擊按鈕后,將所選文件轉(zhuǎn)換并保存到指定文件夾。
  2. 圖片轉(zhuǎn)換:使用 Pillow 庫(kù)來(lái)處理圖片的轉(zhuǎn)換。我們通過(guò) Image.open() 打開(kāi)圖片,調(diào)用 convert("RGB") 方法以確保圖像可以轉(zhuǎn)換為目標(biāo)格式,然后調(diào)用 save() 保存為新的格式。

  3. 錯(cuò)誤處理:如果文件轉(zhuǎn)換失敗或用戶未選擇文件、文件夾等,程序會(huì)彈出錯(cuò)誤消息框,提示用戶。

運(yùn)行和測(cè)試

  • 啟動(dòng)程序后,點(diǎn)擊 “選擇圖片文件” 按鈕,選擇要轉(zhuǎn)換的 .png 文件。
  • 選擇目標(biāo)格式(如 jpeggifbmp 等)。
  • 點(diǎn)擊 “選擇保存文件夾” 按鈕,選擇保存文件的目錄。
  • 最后,點(diǎn)擊 “轉(zhuǎn)換” 按鈕,程序會(huì)將選擇的圖片轉(zhuǎn)換為目標(biāo)格式,并保存在指定文件夾中。

結(jié)果如下

到此這篇關(guān)于使用python創(chuàng)建圖片格式轉(zhuǎn)換器的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)python圖片格式轉(zhuǎn)換器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論