基于Python編寫一個圖片批量修改尺寸工具
前言
在日常辦公和內(nèi)容創(chuàng)作中,我們經(jīng)常需要批量處理大量圖片尺寸。無論是為網(wǎng)站準(zhǔn)備素材,還是為報告統(tǒng)一圖片規(guī)格,手動一張張調(diào)整既費(fèi)時又容易出錯。今天我要分享一個用Python開發(fā)的圖片批量修改尺寸工具,它能幫你輕松解決這個問題。
一、工具功能亮點(diǎn)
這個工具具有以下實(shí)用功能:
- 批量處理:一次性調(diào)整整個文件夾下的所有圖片
- 尺寸自定義:自由設(shè)定需要的寬度和高度
- 智能備份:可選擇創(chuàng)建備份文件夾,防止誤操作
- 格式兼容:支持PNG、JPG、JPEG、BMP、GIF等常見格式
- 操作簡單:圖形化界面,無需編程知識即可使用
二、工具核心代碼解析
工具基于Python的PyQt5和Pillow庫開發(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("請選擇圖片目錄:")
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)備工作-庫的安裝
| 庫 | 用途 | 安裝 |
|---|---|---|
| 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)用場景
電商運(yùn)營:批量統(tǒng)一商品圖片尺寸
新媒體編輯:為公眾號文章準(zhǔn)備統(tǒng)一規(guī)格的圖片
教育培訓(xùn):標(biāo)準(zhǔn)化教學(xué)資料中的插圖
個人相冊:整理手機(jī)拍攝的照片尺寸
五、技術(shù)要點(diǎn)總結(jié)
PyQt5框架:提供了專業(yè)的GUI開發(fā)能力
Pillow庫:強(qiáng)大的圖像處理功能
異常處理:確保程序穩(wěn)定運(yùn)行
try:
# 圖片處理代碼
except Exception as e:
QMessageBox.critical(self, "錯誤", f"處理失敗: {str(e)}")
路徑處理:使用os.path處理跨平臺文件路徑
六、擴(kuò)展思路
這個基礎(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("請選擇圖片目錄:")
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):
"""打開并選擇一個目錄作為圖片數(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) # 注意:這會覆蓋原文件
print(f"已修改圖片 {im} 的尺寸為 {new_width}x{new_height}")
QMessageBox.information(self, "完成", "所有圖片已按指定尺寸修改完畢!")
except ValueError as e:
QMessageBox.critical(self, "錯誤", str(e))
except IOError:
QMessageBox.critical(self, "錯誤", "無法打開圖片文件,請檢查文件格式。")
except Exception as e:
QMessageBox.critical(self, "錯誤", f"未知錯誤: {str(e)}")
if __name__ == "__main__":
app = QApplication([])
window = ImageResizerApp()
window.show()
app.exec_()
以上就是基于Python編寫一個圖片批量修改尺寸工具的詳細(xì)內(nèi)容,更多關(guān)于Python圖片尺寸修改的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)全角半角字符互轉(zhuǎn)的方法
大家都知道在自然語言處理過程中,全角、半角的的不一致會導(dǎo)致信息抽取不一致,因此需要統(tǒng)一。這篇文章通過示例代碼給大家詳細(xì)的介紹了Python實(shí)現(xiàn)全角半角字符互轉(zhuǎn)的方法,有需要的朋友們可以參考借鑒,下面跟著小編一起學(xué)習(xí)學(xué)習(xí)吧。2016-11-11
Python3.8如何解決No module named 'numpy&apos
這篇文章主要介紹了Python3.8如何解決No module named 'numpy'報錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
Numpy實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)(CNN)的示例
這篇文章主要介紹了Numpy實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)(CNN)的示例,幫助大家更好的理解和使用Numpy,感興趣的朋友可以了解下2020-10-10
python在屏幕上點(diǎn)擊特定按鈕或圖像效果實(shí)例
這篇文章主要給大家介紹了關(guān)于python在屏幕上點(diǎn)擊特定按鈕或圖像效果的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-09-09
解析Pytorch中的torch.gather()函數(shù)
本文給大家介紹了Pytorch中的torch.gather()函數(shù),通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-11-11

