基于Python實現(xiàn)一個圖片拆分工具
更新時間:2025年07月06日 10:42:40 作者:封奚澤優(yōu)
這篇文章主要為大家詳細介紹了如何基于Python實現(xiàn)一個圖片拆分工具,可以根據(jù)需要的行數(shù)和列數(shù)進行拆分,感興趣的小伙伴可以跟隨小編一起學習一下
簡單介紹
先自己選擇輸入的圖片,默認是輸出到項目文件夾中,可以自己選擇其他的文件夾,選擇需要拆分的行數(shù)和列數(shù),可以通過deepseek來輸出文件名的格式。
效果圖
完整代碼
import sys import os import shutil from PIL import Image from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QFileDialog, QSpinBox, QGroupBox, QMessageBox) from PyQt5.QtCore import Qt class ImageSplitterApp(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("圖片拆分工具") self.setFixedSize(450, 400) # 稍微增大窗口以適應更多內(nèi)容 # 獲取項目目錄作為默認輸出路徑 self.project_dir = os.path.dirname(os.path.abspath(__file__)) self.default_output_dir = os.path.join(self.project_dir, "split_results") self.output_dir = self.default_output_dir self.image_path = None self.original_filename = None self.init_ui() self.center_window() def center_window(self): """將窗口居中顯示在屏幕上""" screen = QApplication.primaryScreen().geometry() size = self.geometry() self.move( (screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2 ) def init_ui(self): # 主部件和布局 main_widget = QWidget() main_layout = QVBoxLayout() main_layout.setAlignment(Qt.AlignTop) # 圖片選擇區(qū)域 img_group = QGroupBox("圖片選擇") img_layout = QVBoxLayout() self.img_label = QLabel("未選擇圖片") self.img_label.setWordWrap(True) img_btn = QPushButton("選擇圖片") img_btn.clicked.connect(self.select_image) img_layout.addWidget(self.img_label) img_layout.addWidget(img_btn) img_group.setLayout(img_layout) # 拆分設置區(qū)域 split_group = QGroupBox("拆分設置") split_layout = QHBoxLayout() row_layout = QVBoxLayout() row_label = QLabel("行數(shù):") self.row_spin = QSpinBox() self.row_spin.setRange(1, 50) self.row_spin.setValue(2) row_layout.addWidget(row_label) row_layout.addWidget(self.row_spin) col_layout = QVBoxLayout() col_label = QLabel("列數(shù):") self.col_spin = QSpinBox() self.col_spin.setRange(1, 50) self.col_spin.setValue(2) col_layout.addWidget(col_label) col_layout.addWidget(self.col_spin) split_layout.addLayout(row_layout) split_layout.addLayout(col_layout) split_group.setLayout(split_layout) # 輸出信息區(qū)域 output_group = QGroupBox("輸出設置") output_layout = QVBoxLayout() self.output_label = QLabel(f"輸出文件夾: {self.output_dir}") self.output_label.setWordWrap(True) output_btn = QPushButton("更改輸出文件夾") output_btn.clicked.connect(self.select_output_dir) output_layout.addWidget(self.output_label) output_layout.addWidget(output_btn) output_group.setLayout(output_layout) # 操作按鈕 self.split_btn = QPushButton("拆分圖片") self.split_btn.setEnabled(False) self.split_btn.clicked.connect(self.split_image) self.split_btn.setMinimumHeight(40) # 增大按鈕高度 # 添加到主布局 main_layout.addWidget(img_group) main_layout.addWidget(split_group) main_layout.addWidget(output_group) main_layout.addWidget(self.split_btn) main_widget.setLayout(main_layout) self.setCentralWidget(main_widget) def select_image(self): file_path, _ = QFileDialog.getOpenFileName( self, "選擇圖片", "", "圖片文件 (*.png *.jpg *.jpeg *.bmp *.gif)" ) if file_path: self.image_path = file_path self.original_filename = os.path.basename(file_path) display_text = f"已選擇: {self.original_filename}" if len(display_text) > 40: display_text = f"已選擇: ...{self.original_filename[-30:]}" self.img_label.setText(display_text) self.split_btn.setEnabled(True) def select_output_dir(self): dir_path = QFileDialog.getExistingDirectory( self, "選擇輸出文件夾", self.project_dir # 從項目目錄開始 ) if dir_path: self.output_dir = dir_path display_text = f"輸出文件夾: {dir_path}" if len(display_text) > 60: display_text = f"輸出文件夾: ...{dir_path[-50:]}" self.output_label.setText(display_text) def split_image(self): if not self.image_path: QMessageBox.warning(self, "警告", "請先選擇圖片!") return try: rows = self.row_spin.value() cols = self.col_spin.value() img = Image.open(self.image_path) img_width, img_height = img.size # 計算每個子圖的大小 tile_width = img_width // cols tile_height = img_height // rows # 確保輸出目錄存在 os.makedirs(self.output_dir, exist_ok=True) # 復制原始圖片到輸出目錄 original_output_path = os.path.join(self.output_dir, self.original_filename) shutil.copy(self.image_path, original_output_path) # 拆分圖片并保存為 main_數(shù)字.png count = 1 for i in range(rows): for j in range(cols): left = j * tile_width upper = i * tile_height right = left + tile_width lower = upper + tile_height # 確保最后一塊包含剩余部分 if j == cols - 1: right = img_width if i == rows - 1: lower = img_height tile = img.crop((left, upper, right, lower)) # 生成文件名:main_數(shù)字.png output_path = os.path.join(self.output_dir, f"main_{count}.png") tile.save(output_path) count += 1 QMessageBox.information( self, "完成", f"圖片已拆分為 {rows}×{cols} = {count - 1} 個小圖!\n" f"保存到: {self.output_dir}\n\n" f"包含文件:\n" f"- 原始圖片: {self.original_filename}\n" f"- 拆分圖片: main_1.png 到 main_{count - 1}.png" ) except Exception as e: QMessageBox.critical(self, "錯誤", f"處理圖片時出錯:\n{str(e)}") if __name__ == "__main__": app = QApplication(sys.argv) window = ImageSplitterApp() window.show() sys.exit(app.exec_())
結(jié)果如下
到此這篇關于基于Python實現(xiàn)一個圖片拆分工具的文章就介紹到這了,更多相關Python圖片拆分內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python bsddb模塊操作Berkeley DB數(shù)據(jù)庫介紹
這篇文章主要介紹了Python bsddb模塊操作Berkeley DB數(shù)據(jù)庫介紹,這里簡單介紹一些關于bsddb的使用方法,需要的朋友可以參考下2015-04-04Python?裝飾器常用的創(chuàng)建方式及源碼示例解析
裝飾器(decorator)是一種高級Python語法,可以對一個函數(shù)、方法或者類進行加工,這篇文章主要介紹了Python?裝飾器常用的創(chuàng)建方式及解析,需要的朋友可以參考下2022-04-04Python實現(xiàn)提取JSON數(shù)據(jù)中的鍵值對并保存為.csv文件
這篇文章主要為大家詳細介紹了如何基于Python實現(xiàn)讀取JSON文件數(shù)據(jù),并將JSON文件中指定的鍵值對數(shù)據(jù)轉(zhuǎn)換為.csv格式文件,感興趣的小伙伴可以了解下2023-09-09Python 實現(xiàn)加密過的PDF文件轉(zhuǎn)WORD格式
這篇文章主要介紹了Python 實現(xiàn)加密過的PDF文件轉(zhuǎn)WORD格式,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02