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

Python使用PIL構(gòu)建圖片裁剪工具的實現(xiàn)步驟

 更新時間:2025年01月12日 09:56:15   作者:winfredzhang  
這篇博客將為您展示如何使用 wxPython 和 PIL 庫開發(fā)一個圖片裁剪工具,本工具能夠加載圖片,允許用戶通過拖拽選擇框裁剪圖片,并保存裁剪后的結(jié)果,以下是完整代碼和實現(xiàn)步驟,需要的朋友可以參考下

C:\pythoncode\new\cropimageandsave.py

功能特性

  1. 圖片加載:支持加載 JPG 和 PNG 格式的圖片。

  2. 動態(tài)裁剪:通過鼠標(biāo)繪制矩形選擇框進行裁剪。

  3. 縮放適配:圖片會根據(jù)面板大小自動縮放顯示。

  4. 保存裁剪結(jié)果:裁剪后的圖片可以保存為 PNG 文件。

代碼實現(xiàn)

完整代碼如下:

import wx
import os
from PIL import Image
 
class ImageCropperFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title='圖片裁剪工具', size=(800, 600))
        self.init_ui()
        
    def init_ui(self):
        # 創(chuàng)建菜單欄
        menubar = wx.MenuBar()
        file_menu = wx.Menu()
        open_item = file_menu.Append(wx.ID_OPEN, '打開圖片', '打開一個圖片文件')
        menubar.Append(file_menu, '文件')
        self.SetMenuBar(menubar)
        
        # 創(chuàng)建面板和圖片顯示控件
        self.panel = wx.Panel(self)
        self.image_panel = wx.Panel(self.panel)
        self.image_panel.SetBackgroundColour(wx.Colour(200, 200, 200))
        
        # 初始化變量
        self.image = None
        self.bitmap = None
        self.start_pos = None
        self.current_pos = None
        self.is_drawing = False
        
        # 設(shè)置布局
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.image_panel, 1, wx.EXPAND)
        self.panel.SetSizer(sizer)
        
        # 綁定事件
        self.Bind(wx.EVT_MENU, self.on_open, open_item)
        self.image_panel.Bind(wx.EVT_PAINT, self.on_paint)
        self.image_panel.Bind(wx.EVT_LEFT_DOWN, self.on_left_down)
        self.image_panel.Bind(wx.EVT_LEFT_UP, self.on_left_up)
        self.image_panel.Bind(wx.EVT_MOTION, self.on_motion)
        
    def on_open(self, event):
        # 打開文件對話框
        with wx.FileDialog(self, "選擇圖片文件", 
                          wildcard="圖片文件 (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png",
                          style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
            
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return
            
            # 加載圖片
            pathname = fileDialog.GetPath()
            self.load_image(pathname)
            self.image_path = pathname
    
    def load_image(self, path):
        # 使用PIL加載圖片
        self.pil_image = Image.open(path)
        # 轉(zhuǎn)換為wx.Bitmap
        self.image = wx.Image(path, wx.BITMAP_TYPE_ANY)
        # 調(diào)整圖片大小以適應(yīng)窗口
        self.scale_image()
        self.Refresh()
    
    def scale_image(self):
        # 獲取面板大小
        panel_size = self.image_panel.GetSize()
        # 計算縮放比例
        width_ratio = panel_size.width / self.image.GetWidth()
        height_ratio = panel_size.height / self.image.GetHeight()
        scale = min(width_ratio, height_ratio)
        
        # 縮放圖片
        new_width = int(self.image.GetWidth() * scale)
        new_height = int(self.image.GetHeight() * scale)
        self.image = self.image.Scale(new_width, new_height)
        self.bitmap = wx.Bitmap(self.image)
        
        # 保存縮放比例用于裁剪
        self.scale_factor = scale
    
    def on_paint(self, event):
        dc = wx.PaintDC(self.image_panel)
        if self.bitmap:
            dc.DrawBitmap(self.bitmap, 0, 0)
        
        # 繪制選擇框
        if self.start_pos and self.current_pos:
            dc.SetPen(wx.Pen(wx.RED, 1, wx.PENSTYLE_DOT))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            x = min(self.start_pos[0], self.current_pos[0])
            y = min(self.start_pos[1], self.current_pos[1])
            w = abs(self.current_pos[0] - self.start_pos[0])
            h = abs(self.current_pos[1] - self.start_pos[1])
            dc.DrawRectangle(x, y, w, h)
    
    def on_left_down(self, event):
        self.start_pos = event.GetPosition()
        self.current_pos = self.start_pos
        self.is_drawing = True
    
    def on_motion(self, event):
        if self.is_drawing:
            self.current_pos = event.GetPosition()
            self.Refresh()
    
    def on_left_up(self, event):
        if self.is_drawing:
            self.is_drawing = False
            # 獲取選擇區(qū)域
            x1 = min(self.start_pos[0], self.current_pos[0])
            y1 = min(self.start_pos[1], self.current_pos[1])
            x2 = max(self.start_pos[0], self.current_pos[0])
            y2 = max(self.start_pos[1], self.current_pos[1])
            
            # 轉(zhuǎn)換回原始圖片坐標(biāo)
            orig_x1 = int(x1 / self.scale_factor)
            orig_y1 = int(y1 / self.scale_factor)
            orig_x2 = int(x2 / self.scale_factor)
            orig_y2 = int(y2 / self.scale_factor)
            
            # 裁剪圖片
            cropped = self.pil_image.crop((orig_x1, orig_y1, orig_x2, orig_y2))
            
            # 生成保存路徑
            directory = os.path.dirname(self.image_path)
            filename = os.path.splitext(os.path.basename(self.image_path))[0]
            save_path = os.path.join(directory, f"{filename}_cropped.png")
            
            # 保存裁剪后的圖片
            cropped.save(save_path)
            
            # 顯示成功消息
            wx.MessageBox(f"裁剪后的圖片已保存至:\n{save_path}", 
                         "保存成功", 
                         wx.OK | wx.ICON_INFORMATION)
            
            # 重置選擇區(qū)域
            self.start_pos = None
            self.current_pos = None
            self.Refresh()
 
if __name__ == '__main__':
    app = wx.App()
    frame = ImageCropperFrame()
    frame.Show()
    app.MainLoop()

核心實現(xiàn)

圖片加載與縮放

使用 PIL.Image 加載圖片,并通過 wx.Image 將其轉(zhuǎn)換為適配 wxPython 的格式。同時,通過計算縮放比例,確保圖片適配顯示區(qū)域。

繪制矩形選擇框

利用 wx.PaintDC 繪制矩形選擇框,在鼠標(biāo)事件(按下、移動、釋放)中動態(tài)更新選擇框。

裁剪與保存

通過 PIL.Image.crop 方法,根據(jù)用戶選擇的區(qū)域裁剪圖片,并自動生成裁剪后的文件路徑進行保存。

運行結(jié)果

總結(jié)

此工具簡單實用,能夠快速完成圖片裁剪任務(wù)。您可以根據(jù)實際需求進一步擴展,例如添加更多格式支持或多圖片批量裁剪功能。歡迎嘗試并提出您的建議!

到此這篇關(guān)于Python使用PIL構(gòu)建圖片裁剪工具的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)Python PIL圖片裁剪工具內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python高級用法總結(jié)

    Python高級用法總結(jié)

    Python很棒,它有很多高級用法值得細(xì)細(xì)思索,學(xué)習(xí)使用。本文將根據(jù)日常使用,總結(jié)介紹Python的一組高級特性,包括:列表推導(dǎo)式、迭代器和生成器、裝飾器
    2018-05-05
  • 詳解Python中的正則表達(dá)式

    詳解Python中的正則表達(dá)式

    正則表達(dá)式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。本文給大家?guī)砹藀ython中的正則表達(dá)式,感興趣的朋友一起看看吧
    2018-07-07
  • ?分享4款Python 自動數(shù)據(jù)分析神器

    ?分享4款Python 自動數(shù)據(jù)分析神器

    這篇文章主要給大家分享的是4款Python 自動數(shù)據(jù)分析神器,我給大家分享 4 款常用的EDA工具,它們可以自動產(chǎn)出統(tǒng)計數(shù)據(jù)和圖表,為我們節(jié)省大量時間,需要的朋友可以參考一下
    2022-03-03
  • python?Sweetviz探索性數(shù)據(jù)可視化分析庫使用特征詳解

    python?Sweetviz探索性數(shù)據(jù)可視化分析庫使用特征詳解

    這篇文章主要為大家介紹了python?Sweetviz探索性數(shù)據(jù)可視化分析庫特征使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Python單元測試實例詳解

    Python單元測試實例詳解

    這篇文章主要介紹了Python單元測試,結(jié)合實例形式詳細(xì)分析了Python單元測試模塊的功能、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下
    2018-05-05
  • python 隨機生成10位數(shù)密碼的實現(xiàn)代碼

    python 隨機生成10位數(shù)密碼的實現(xiàn)代碼

    這篇文章主要介紹了python 隨機生成10位數(shù)密碼的實現(xiàn)代碼,在文中給大家提到了生成隨機密碼要實現(xiàn)的功能,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-06-06
  • Python讀取文件的8種常用方式

    Python讀取文件的8種常用方式

    這篇文章主要給大家介紹了關(guān)于Python讀取文件的8種常用方式,在編程語言中,文件讀寫是最常見的IO操作,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-09-09
  • python time時間庫詳解

    python time時間庫詳解

    Python中內(nèi)置了一些與時間處理相關(guān)的庫,如time、datatime和calendar庫,這篇文章主要介紹了python-time時間庫,需要的朋友可以參考下
    2022-08-08
  • 詳解django中Template語言

    詳解django中Template語言

    Django是一個開放源代碼的Web應(yīng)用框架,由Python寫成。這篇文章給大家介紹django中Template語言,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友參考下吧
    2020-02-02
  • 使用TensorFlow實現(xiàn)SVM

    使用TensorFlow實現(xiàn)SVM

    這篇文章主要為大家詳細(xì)介紹了使用TensorFlow實現(xiàn)SVM的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09

最新評論