前段時間寫了個比較簡單的批量水印添加的python實作方式,將某個檔案夾下面的圖片全部添加上水印,
【閱讀全文】
今天正好有時間就做了一個UI應用的封裝,這樣不需要知道python直接下載exe的應用程式使用即可,
有需要'批量圖片水印添加器'的朋友可以直接跳過到文章末尾獲取下載方式,下載.exe的可執行應用直接使用即可,下面主要來介紹一下實作程序,
首先,還是老規矩介紹一下在開發程序中需要用到的python非標準庫,由于這些庫都是之前使用過的,
所以這里就直接匯入到代碼塊中,如果沒有的話直接使用pip的方式進行安裝即可,
# It imports all the classes, attributes, and methods of the PyQt5.QtCore module into the global symbol table.
from PyQt5.QtCore import *
# It imports all the classes, attributes, and methods of the PyQt5.QtWidgets module into the global symbol table.
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QTextBrowser, QLineEdit, QPushButton, \
QFormLayout, QFileDialog, QLabel
# It imports all the classes, attributes, and methods of the PyQt5.QtGui module into the global symbol table.
from PyQt5.QtGui import QIcon, QFont, QTextCursor
# It imports the sys module.
import sys
# It imports the os module.
import os
# It imports the logger from the loguru module.
from loguru import logger
# It imports the add_mark function from the marker module in the watermarker package.
from watermarker.marker import add_mark
以上匯入的python庫就是在整個UI桌面應用開發程序中需要用到的,完成直接我們新建UI類PicWaterUI專門用來寫一些關于桌面應用的布局,
其中包括按鈕、輸入框等組件,此外將組件關聯的槽函式也寫入到這個類中,這樣有利于統一管理,代碼量比較多有需要的朋友耐心閱讀,

# This class is a widget that contains a QLabel and a QPushButton
class PicWaterUI(QWidget):
def __init__(self):
"""
A constructor. It is called when an object is created from a class and it allows the class to initialize the
attributes of a class.
"""
super(PicWaterUI, self).__init__()
self.init_ui()
def init_ui(self):
"""
This function initializes the UI.
"""
self.setWindowTitle('批量圖片水印添加器 公眾號:Python 集中營!')
self.setWindowIcon(QIcon('water.ico'))
self.brower = QTextBrowser()
self.brower.setFont(QFont('宋體', 8))
self.brower.setReadOnly(True)
self.brower.setPlaceholderText('處理行程展示區域...')
self.brower.ensureCursorVisible()
self.pic_file_path = QLineEdit()
self.pic_file_path.setPlaceholderText('源批量圖片路徑')
self.pic_file_path.setReadOnly(True)
self.pic_file_path_btn = QPushButton()
self.pic_file_path_btn.setText('源圖片路徑')
self.pic_file_path_btn.clicked.connect(self.pic_file_path_btn_click)
self.new_pic_file_path = QLineEdit()
self.new_pic_file_path.setPlaceholderText('新圖片存盤路徑')
self.new_pic_file_path.setReadOnly(True)
self.new_pic_file_path_btn = QPushButton()
self.new_pic_file_path_btn.setText('保存路徑')
self.new_pic_file_path_btn.clicked.connect(self.new_pic_file_path_btn_click)
self.water_current_label = QLabel()
self.water_current_label.setText('水印內容:')
self.water_current_in = QLineEdit()
self.water_current_in.setPlaceholderText('Python 集中營')
self.water_angle_label = QLabel()
self.water_angle_label.setText('水印角度:')
self.water_angle_in = QLineEdit()
self.water_angle_in.setPlaceholderText('30')
self.water_back_label = QLabel()
self.water_back_label.setText('水印透明度:')
self.water_back_in = QLineEdit()
self.water_back_in.setPlaceholderText('0.3')
self.water_font_label = QLabel()
self.water_font_label.setText('水印字體大小:')
self.water_font_in = QLineEdit()
self.water_font_in.setPlaceholderText('30')
self.water_space_label = QLabel()
self.water_space_label.setText('水印間隔:')
self.water_space_in = QLineEdit()
self.water_space_in.setPlaceholderText('40')
self.water_color_label = QLabel()
self.water_color_label.setText('水印顏色:')
self.water_color_in = QLineEdit()
self.water_color_in.setPlaceholderText('#8B8B1B')
self.start_btn = QPushButton()
self.start_btn.setText('開始添加水印')
self.start_btn.clicked.connect(self.start_btn_click)
hbox = QHBoxLayout()
hbox.addWidget(self.brower)
fbox = QFormLayout()
fbox.addRow(self.pic_file_path, self.pic_file_path_btn)
fbox.addRow(self.new_pic_file_path, self.new_pic_file_path_btn)
fbox.addRow(self.water_current_label, self.water_current_in)
fbox.addRow(self.water_angle_label, self.water_angle_in)
fbox.addRow(self.water_back_label, self.water_back_in)
fbox.addRow(self.water_font_label, self.water_font_in)
fbox.addRow(self.water_space_label, self.water_space_in)
fbox.addRow(self.water_color_label, self.water_color_in)
v_vbox = QVBoxLayout()
v_vbox.addWidget(self.start_btn)
vbox = QVBoxLayout()
vbox.addLayout(fbox)
vbox.addLayout(v_vbox)
hbox.addLayout(vbox)
self.thread_ = PicWaterThread(self)
self.thread_.message.connect(self.show_message)
self.thread_.finished.connect(self.finshed)
self.setLayout(hbox)
def show_message(self, text):
"""
It shows a message
:param text: The text to be displayed
"""
cursor = self.brower.textCursor()
cursor.movePosition(QTextCursor.End)
self.brower.append(text)
self.brower.setTextCursor(cursor)
self.brower.ensureCursorVisible()
def pic_file_path_btn_click(self):
"""
It opens a file dialog box and allows the user to select a file.
"""
pic_file_path = QFileDialog.getExistingDirectory(self, '選擇檔案夾', os.getcwd())
self.pic_file_path.setText(pic_file_path)
def new_pic_file_path_btn_click(self):
"""
This function opens a file dialog box and allows the user to select a file to save the output to.
"""
new_pic_file_path = QFileDialog.getExistingDirectory(self, '選擇檔案夾', os.getcwd())
self.new_pic_file_path.setText(new_pic_file_path)
def start_btn_click(self):
"""
A function that is called when the start button is clicked.
"""
self.thread_.start()
self.start_btn.setEnabled(False)
def finshed(self, finished):
"""
:param finished: A boolean value that is True if the download is finished, False otherwise
"""
if finished is True:
self.start_btn.setEnabled(True)
頁面布局及組件部分完成之后就是業務的具體實作部分了,業務就是實作批量添加水印的效果,
這里新建了一個PicWaterThread類作為UI桌面應用的子執行緒專門將業務實作的部分寫到這個類中,
業務部分和主執行緒直接分離時,一來從代碼層面上看起來比較明了,二來在子執行緒執行業務比較慢的情況下不至于導致主執行緒出現卡死的情況發生,
為了達到業務和界面分離的效果,下面PicWaterThread子執行緒的run函式里面就是具體的業務實作部分,
# This class is a subclass of QThread, and it's used to watermark pictures
class PicWaterThread(QThread):
# A signal that is emitted when a message is received.
message = pyqtSignal(str)
# A signal that is emitted when the download is finished.
finished = pyqtSignal(bool)
def __init__(self, parent=None):
"""
A constructor that initializes the class.
:param parent: The parent widget
"""
super(PicWaterThread, self).__init__(parent)
self.working = True
self.parent = parent
def __del__(self):
"""
A destructor. It is called when the object is destroyed.
"""
self.working = True
self.wait()
def run(self) -> None:
"""
> This function runs the program
"""
try:
directory = self.parent.pic_file_path.text().strip()
water_name = self.parent.water_current_in.text().strip()
new_directory = self.parent.new_pic_file_path.text().strip()
water_angle_in = self.parent.water_angle_in.text().strip()
water_back_in = self.parent.water_back_in.text().strip()
water_font_in = self.parent.water_font_in.text().strip()
water_space_in = self.parent.water_space_in.text().strip()
color = self.parent.water_color_in.text().strip()
self.message.emit('源檔案路徑:{}'.format(directory))
self.message.emit('水印內容:{}'.format(water_name))
self.message.emit('保存檔案路徑:{}'.format(new_directory))
self.message.emit('水印角度:{}'.format(water_angle_in))
self.message.emit('水印透明度:{}'.format(water_back_in))
self.message.emit('水印字體大小:{}'.format(water_font_in))
self.message.emit('水印間隔:{}'.format(water_space_in))
self.message.emit('水印顏色:{}'.format(color))
if directory is None or water_name is None:
logger.info('檔案夾地址或水印名稱不能為空!')
return
for file_name in os.listdir(directory):
logger.info('當前檔案名稱:{0},即將開始添加水印操作!'.format(file_name))
self.message.emit('當前檔案名稱:{0},即將開始添加水印操作!'.format(file_name))
add_mark(file=os.path.join(directory, file_name), out=new_directory, mark=water_name,
opacity=float(water_back_in), angle=int(water_angle_in), space=int(water_space_in),
size=int(water_font_in), color=color)
self.message.emit('當前檔案名稱:{0},已經完成添加水印操作!'.format(file_name))
logger.info('當前檔案名稱:{0},已經完成添加水印操作!'.format(file_name))
self.finished.emit(True)
except Exception as e:
self.message.emit('檔案內容讀取或格式化發生例外!')
self.finished.emit(True)
完成業務以及頁面應用的開發之后,我們使用main函式將整個桌面應用調起來,這種范式基本上每個桌面應用的使用是一樣的,
如果需要好看一些的話還可以加上我們之前提到過的各種樣式主題的應用,在公眾號主頁上進行搜索就可以找到之前發表的相關的文章,
if __name__ == '__main__':
app = QApplication(sys.argv)
main = PicWaterUI()
main.show()
sys.exit(app.exec_())
最后,我們找了兩張斗羅大陸'唐三'的照片測驗一下效果如何,使用上面的main函式啟動整個應用之后是怎樣的,
大家可以直接在應用上面選擇需要批量添加水印的圖片路徑以及添加完成后需要保存的地方,
并且可以在生成時在桌面應用上調整水印相關的各種引數,包括水印的大小、尺寸、間隔、顏色等等,這樣就可以根據自己的需要對批量圖片制作屬于的水印效果了,

下面是將'唐三'的照片經過該頁面轉換以后的效果了,基本上滿足我對大批圖片添加相同的水印的要求了,
接下來看一下'修羅唐三'被我們添加了'Python 集中營'的水印以后變成什么樣了,


有需要.exe可執行應用的朋友在公眾號內直接回復'批量圖片水印添加器'獲取網盤的下載鏈接,應用我們已經打包好了有需要的話直接下載即可,
以后字串中的字符提取校驗就用這個了,效果不錯!
為方便資料分析,實作Python物件與DataFrame資料的相互轉換!
python資料分析透視表,定制你的分析計算需求!
歡迎關注作者公眾號【Python 集中營】,專注于后端編程,每天更新技術干貨,不定時分享各類資料!轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514166.html
標籤:其他
