基于Python編寫一個(gè)圖片批量修改尺寸工具
前言
在日常辦公和內(nèi)容創(chuàng)作中,我們經(jīng)常需要批量處理大量圖片尺寸。無論是為網(wǎng)站準(zhǔn)備素材,還是為報(bào)告統(tǒng)一圖片規(guī)格,手動(dòng)一張張調(diào)整既費(fèi)時(shí)又容易出錯(cuò)。今天我要分享一個(gè)用Python開發(fā)的圖片批量修改尺寸工具,它能幫你輕松解決這個(gè)問題。
一、工具功能亮點(diǎn)
這個(gè)工具具有以下實(shí)用功能:
- 批量處理:一次性調(diào)整整個(gè)文件夾下的所有圖片
- 尺寸自定義:自由設(shè)定需要的寬度和高度
- 智能備份:可選擇創(chuàng)建備份文件夾,防止誤操作
- 格式兼容:支持PNG、JPG、JPEG、BMP、GIF等常見格式
- 操作簡(jiǎn)單:圖形化界面,無需編程知識(shí)即可使用
二、工具核心代碼解析
工具基于Python的PyQt5和Pillow庫(kù)開發(fā),下面是核心代碼結(jié)構(gòu):
import os
from PIL import Image
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QPushButton, QListWidget,
QLineEdit, QMessageBox, QFileDialog)
1. 界面布局設(shè)計(jì)
def init_ui(self):
# 主窗口設(shè)置
self.setWindowTitle("圖片批量修改尺寸工具")
self.setGeometry(100, 100, 600, 500)
# 主布局
main_layout = QVBoxLayout()
# 文件夾選擇部分
folder_layout = QHBoxLayout()
self.label_folder_path = QLabel("請(qǐng)選擇圖片目錄:")
self.button_choose_folder = QPushButton("選擇目錄")
folder_layout.addWidget(self.label_folder_path)
folder_layout.addWidget(self.button_choose_folder)
# 圖片列表
self.image_list = QListWidget()
# 尺寸輸入部分
size_layout = QHBoxLayout()
# ...寬度和高度輸入框設(shè)置...
# 操作按鈕
self.button_resize = QPushButton("批量修改尺寸")
# 將所有部件添加到主布局
main_layout.addLayout(folder_layout)
main_layout.addWidget(self.image_list)
main_layout.addLayout(size_layout)
main_layout.addWidget(self.button_resize)
2. 核心功能實(shí)現(xiàn)
圖片尺寸調(diào)整函數(shù)是工具的核心:
def resize_images(self):
# 獲取用戶輸入的尺寸
new_width = int(self.entry_width.text())
new_height = int(self.entry_height.text())
# 遍歷處理每張圖片
for i in range(self.image_list.count()):
img_name = self.image_list.item(i).text()
img_path = os.path.join(self.image_folder_path, img_name)
# 使用Pillow打開并調(diào)整圖片
with Image.open(img_path) as img:
resized_img = img.resize((new_width, new_height), Image.Resampling.BICUBIC)
# 根據(jù)用戶選擇保存到備份文件夾或覆蓋原文件
if self.backup_mode:
backup_path = os.path.join(self.backup_folder_path, img_name)
resized_img.save(backup_path)
else:
resized_img.save(img_path)
三、工具使用教程
1. 準(zhǔn)備工作-庫(kù)的安裝
| 庫(kù) | 用途 | 安裝 |
|---|---|---|
| PyQt5 | 界面設(shè)計(jì) | pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| pillow | 圖片處理 | pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
2. 使用步驟
運(yùn)行程序,點(diǎn)擊"選擇目錄"按鈕
選取包含需要修改尺寸的圖片文件夾
在寬度和高度輸入框中輸入目標(biāo)尺寸
點(diǎn)擊"批量修改尺寸"按鈕
根據(jù)需要選擇是否創(chuàng)建備份
3. 效果展示


四、實(shí)際應(yīng)用場(chǎng)景
電商運(yùn)營(yíng):批量統(tǒng)一商品圖片尺寸
新媒體編輯:為公眾號(hào)文章準(zhǔn)備統(tǒng)一規(guī)格的圖片
教育培訓(xùn):標(biāo)準(zhǔn)化教學(xué)資料中的插圖
個(gè)人相冊(cè):整理手機(jī)拍攝的照片尺寸
五、技術(shù)要點(diǎn)總結(jié)
PyQt5框架:提供了專業(yè)的GUI開發(fā)能力
Pillow庫(kù):強(qiáng)大的圖像處理功能
異常處理:確保程序穩(wěn)定運(yùn)行
try:
# 圖片處理代碼
except Exception as e:
QMessageBox.critical(self, "錯(cuò)誤", f"處理失敗: {str(e)}")
路徑處理:使用os.path處理跨平臺(tái)文件路徑
六、擴(kuò)展思路
這個(gè)基礎(chǔ)工具還可以進(jìn)一步擴(kuò)展:
添加圖片質(zhì)量調(diào)整選項(xiàng)
支持按比例縮放而非固定尺寸
增加圖片格式轉(zhuǎn)換功能
添加拖放文件支持
實(shí)現(xiàn)預(yù)設(shè)尺寸模板
七、完整代碼獲取
import os
from PIL import Image
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QListWidget, QLineEdit, QScrollArea,
QMessageBox, QFileDialog)
from PyQt5.QtCore import Qt
class ImageResizerApp(QMainWindow):
def __init__(self):
super().__init__()
self.image_folder_path = ""
self.backup_folder_path = ""
self.init_ui()
def init_ui(self):
self.setWindowTitle("圖片批量修改尺寸工具")
self.setGeometry(100, 100, 600, 500)
# 主部件
main_widget = QWidget()
self.setCentralWidget(main_widget)
# 主布局
main_layout = QVBoxLayout()
main_widget.setLayout(main_layout)
# 文件夾選擇部分
folder_layout = QHBoxLayout()
self.label_folder_path = QLabel("請(qǐng)選擇圖片目錄:")
self.button_choose_folder = QPushButton("選擇目錄")
self.button_choose_folder.clicked.connect(self.open_directory)
folder_layout.addWidget(self.label_folder_path)
folder_layout.addWidget(self.button_choose_folder)
main_layout.addLayout(folder_layout)
# 圖片列表
self.image_list = QListWidget()
main_layout.addWidget(self.image_list)
# 尺寸輸入部分
size_layout = QHBoxLayout()
width_layout = QVBoxLayout()
self.label_width = QLabel("新寬度:")
self.entry_width = QLineEdit()
width_layout.addWidget(self.label_width)
width_layout.addWidget(self.entry_width)
height_layout = QVBoxLayout()
self.label_height = QLabel("新高度:")
self.entry_height = QLineEdit()
height_layout.addWidget(self.label_height)
height_layout.addWidget(self.entry_height)
size_layout.addLayout(width_layout)
size_layout.addLayout(height_layout)
main_layout.addLayout(size_layout)
# 操作按鈕
self.button_resize = QPushButton("批量修改尺寸")
self.button_resize.clicked.connect(self.resize_images)
main_layout.addWidget(self.button_resize)
def open_directory(self):
"""打開并選擇一個(gè)目錄作為圖片數(shù)據(jù)源"""
folder = QFileDialog.getExistingDirectory(self, "選擇圖片目錄")
if folder:
self.image_folder_path = folder
self.label_folder_path.setText(f"已選擇目錄: {folder}")
self.update_image_list()
def update_image_list(self):
"""更新并顯示圖片列表"""
self.image_list.clear()
if self.image_folder_path:
for im in os.listdir(self.image_folder_path):
if im.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
self.image_list.addItem(im)
def create_backup_folder(self):
"""創(chuàng)建備份文件夾"""
self.backup_folder_path = os.path.join(self.image_folder_path, "resized")
if not os.path.exists(self.backup_folder_path):
os.makedirs(self.backup_folder_path)
def resize_images(self):
"""批量修改圖片尺寸"""
if self.image_list.count() == 0:
QMessageBox.warning(self, "警告", "沒有圖片可供調(diào)整尺寸!")
return
reply = QMessageBox.question(self, "提示", "是否創(chuàng)建備份文件夾?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
should_create_backup = reply == QMessageBox.Yes
if should_create_backup:
self.create_backup_folder()
try:
new_width = int(self.entry_width.text())
new_height = int(self.entry_height.text())
if new_width <= 0 or new_height <= 0:
raise ValueError("寬度和高度必須大于0")
for i in range(self.image_list.count()):
im = self.image_list.item(i).text()
img_path = os.path.join(self.image_folder_path, im)
with Image.open(img_path) as img:
resized_img = img.resize((new_width, new_height), Image.Resampling.BICUBIC)
if should_create_backup:
backup_img_path = os.path.join(self.backup_folder_path, im)
resized_img.save(backup_img_path)
print(f"已修改圖片 {im} 的尺寸為 {new_width}x{new_height} 并保存到備份文件夾。")
else:
resized_img.save(img_path) # 注意:這會(huì)覆蓋原文件
print(f"已修改圖片 {im} 的尺寸為 {new_width}x{new_height}")
QMessageBox.information(self, "完成", "所有圖片已按指定尺寸修改完畢!")
except ValueError as e:
QMessageBox.critical(self, "錯(cuò)誤", str(e))
except IOError:
QMessageBox.critical(self, "錯(cuò)誤", "無法打開圖片文件,請(qǐng)檢查文件格式。")
except Exception as e:
QMessageBox.critical(self, "錯(cuò)誤", f"未知錯(cuò)誤: {str(e)}")
if __name__ == "__main__":
app = QApplication([])
window = ImageResizerApp()
window.show()
app.exec_()
以上就是基于Python編寫一個(gè)圖片批量修改尺寸工具的詳細(xì)內(nèi)容,更多關(guān)于Python圖片尺寸修改的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python模擬預(yù)測(cè)一下新型冠狀病毒肺炎的數(shù)據(jù)
這篇文章主要介紹了python模擬預(yù)測(cè)一下新型冠狀病毒肺炎的數(shù)據(jù) ,需要的朋友可以參考下2020-02-02
在keras里面實(shí)現(xiàn)計(jì)算f1-score的代碼
這篇文章主要介紹了在keras里面實(shí)現(xiàn)計(jì)算f1-score的代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python利用Turtle繪制Technoblade的示例代碼
國(guó)外一位在YouTube擁有上千萬粉絲的我的世界游戲主播Technoblade因癌癥與世長(zhǎng)辭,為了紀(jì)念他,特地寫了這篇文章,教大家用Turtle繪制出Technoblade,快跟隨小編一起學(xué)習(xí)一下吧2023-01-01
Python實(shí)現(xiàn)的ini文件操作類分享
這篇文章主要介紹了Python實(shí)現(xiàn)的ini文件操作類分享,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2014-11-11
使用 Python 獲取 Linux 系統(tǒng)信息的代碼
在本文中,我們將會(huì)探索使用Python編程語言工具來檢索Linux系統(tǒng)各種信息,需要的朋友可以參考下2014-07-07
Python使用Joblib模塊實(shí)現(xiàn)加快任務(wù)處理速度
在Python編程中,處理大規(guī)模數(shù)據(jù)或者進(jìn)行復(fù)雜的計(jì)算任務(wù)時(shí),通常需要考慮如何提高程序的運(yùn)行效率,本文主要介紹了如何使用Joblib模塊來加快任務(wù)處理速度,需要的可以參考下2024-03-03

