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

基于Python實(shí)現(xiàn)一個(gè)圖片拆分工具

 更新時(shí)間:2025年07月06日 10:42:40   作者:封奚澤優(yōu)  
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)一個(gè)圖片拆分工具,可以根據(jù)需要的行數(shù)和列數(shù)進(jìn)行拆分,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

簡(jiǎn)單介紹

先自己選擇輸入的圖片,默認(rèn)是輸出到項(xiàng)目文件夾中,可以自己選擇其他的文件夾,選擇需要拆分的行數(shù)和列數(shù),可以通過(guò)deepseek來(lái)輸出文件名的格式。

效果圖

完整代碼 

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)  # 稍微增大窗口以適應(yīng)更多內(nèi)容

        # 獲取項(xiàng)目目錄作為默認(rèn)輸出路徑
        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)

        # 拆分設(shè)置區(qū)域
        split_group = QGroupBox("拆分設(shè)置")
        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("輸出設(shè)置")
        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  # 從項(xiàng)目目錄開(kāi)始
        )

        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, "警告", "請(qǐng)先選擇圖片!")
            return

        try:
            rows = self.row_spin.value()
            cols = self.col_spin.value()

            img = Image.open(self.image_path)
            img_width, img_height = img.size

            # 計(jì)算每個(gè)子圖的大小
            tile_width = img_width // cols
            tile_height = img_height // rows

            # 確保輸出目錄存在
            os.makedirs(self.output_dir, exist_ok=True)

            # 復(fù)制原始圖片到輸出目錄
            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} 個(gè)小圖!\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, "錯(cuò)誤", f"處理圖片時(shí)出錯(cuò):\n{str(e)}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ImageSplitterApp()
    window.show()
    sys.exit(app.exec_())

結(jié)果如下 

到此這篇關(guān)于基于Python實(shí)現(xiàn)一個(gè)圖片拆分工具的文章就介紹到這了,更多相關(guān)Python圖片拆分內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論