草庐IT

周末自制了一个批量图片水印添加器!

Python 集中营 2023-04-19 原文

前段时间写了个比较简单的批量水印添加的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数据分析透视表,定制你的分析计算需求!

有关周末自制了一个批量图片水印添加器!的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  4. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  8. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  9. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  10. ruby-on-rails - Ruby on Rails - 为文本区域和图片生成列 - 2

    我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数

随机推荐