Python 实现给图片加文字或logo水印

 更新时间:2021年11月22日 09:26:14   作者:剑客阿良_ALiang  
本文主要为大家介绍了给图片添加文字或者logo图片水印的python工具,从而打造你的专属图片。代码简洁易懂,感兴趣的小伙伴可以了解一下

前言

本文提供给图片添加文字或者logo图片水印的python工具,打造专属图片。

环境依赖

ffmpeg环境安装,ffmpy安装:

pip install ffmpy -i https://pypi.douban.com/simple

代码

上代码。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : image_add_watermark_tool.py
@ide    : PyCharm
@time   : 2021-11-20 14:18:13
"""
import os
import uuid
from ffmpy import FFmpeg
 
 
# 图片加文字水印
def image_add_text(
        image_path: str,
        output_dir: str,
        text: str,
        font_name: str,
        font_size=100,
        position=(0, 0),
        font_color='blue',
        box=1,
        box_color='white'):
    ext = _check_format(image_path)
    result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
    ff = FFmpeg(
        inputs={
            image_path: None},
        outputs={
            result: '-vf drawtext=\"fontsize={}:fontfile={}:text=\'{}\':x={}:y={}:fontcolor={}:box={}:boxcolor={}\"'.format(
                font_size,
                font_name,
                text,
                position[0],
                position[1],
                font_color,
                box,
                box_color)})
    print(ff.cmd)
    ff.run()
    return result
 
 
# 图片添加logo
def image_add_logo(
        image_path: str,
        output_dir: str,
        logo_path: str,
        position=(0, 0)):
    ext = _check_format(image_path)
    result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
    filter_cmd = '-vf \"movie=\'{}\' [wm];[in] [wm]overlay={}:{} [out]\"'
    ff = FFmpeg(
        inputs={
            image_path: None}, outputs={
            result: filter_cmd.format(logo_path, position[0], position[1])})
    print(ff.cmd)
    ff.run()
    return result
 
 
def _check_format(image_path: str):
    ext = os.path.basename(image_path).strip().split('.')[-1]
    if ext not in ['png', 'jpg']:
        raise Exception('format error')
    return ext
 

代码说明

1、image_add_text方法给图片添加文字水印方法,主要参数为:图片路径、输出目录、

水印文字、字体名称、字体大小(默认100)、文字左上角坐标(默认0:0)、文字颜色(默认蓝色)、是否需要背景(默认需要为1,不需要为0)、背景色(默认白色)。

2、image_add_logo方法给图片添加logo,主要参数为:图片路径、输出目录、logo图片地址、文字左上角坐标(默认0:0)。

3、注意logo地址如果有类似C:/这种windows盘的路径情况,需要对":"进行转义。后面验证的时候,可以看看我给的参数。

4、文件名为了避免重复,采用了uuid作为文件名。

5、图片后缀格式校验只有两种,按需添加即可。

验证一下

准备的素材如下,分别为图片与logo图

验证代码

if __name__ == '__main__':
    print(
        image_add_text(
            'C:/Users/huyi/Desktop/1.jpg',
            'C:/Users/huyi/Desktop/', '剑客阿良_ALiang', '微软雅黑', box=0))
    print(
        image_add_logo(
            'C:/Users/huyi/Desktop/1.jpg',
            'C:/Users/huyi/Desktop/', 'C\\:/Users/huyi/Desktop/logo.png', (30, 10)))

注意我给出的logo地址路径有什么不同。

执行结果

PyDev console: starting.
Python 3.6.13 |Anaconda, Inc.| (default, Mar 16 2021, 11:37:27) [MSC v.1916 64 bit (AMD64)] on win32
runfile('D:/spyder/csdn/image_add_watermark_tool.py', wdir='D:/spyder/csdn')
ffmpeg -i C:/Users/huyi/Desktop/1.jpg -vf drawtext=fontsize=100:fontfile=微软雅黑:text='剑客阿良_ALiang':x=0:y=0:fontcolor=blue:box=0:boxcolor=white C:/Users/huyi/Desktop/2226d7e0-5166-4ffd-ba95-9ca7d9d6f72d.jpg
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, image2, from 'C:/Users/huyi/Desktop/1.jpg':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 181106 kb/s
    Stream #0:0: Video: mjpeg (Progressive), yuvj444p(pc, bt470bg/unknown/unknown), 3840x2160, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
Press [q] to stop, [?] for help
Fontconfig error: Cannot load default config file
[Parsed_drawtext_0 @ 0000014152ea5400] Using "C:/Windows/fonts/msyh.ttc"
Output #0, image2, to 'C:/Users/huyi/Desktop/2226d7e0-5166-4ffd-ba95-9ca7d9d6f72d.jpg':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: mjpeg, yuvj444p(pc), 3840x2160, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 mjpeg
    Side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A
frame=    1 fps=0.0 q=11.5 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.158x    
video:634kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
C:/Users/huyi/Desktop/2226d7e0-5166-4ffd-ba95-9ca7d9d6f72d.jpg
ffmpeg -i C:/Users/huyi/Desktop/1.jpg -vf "movie='C\:/Users/huyi/Desktop/logo.png' [wm];[in] [wm]overlay=30:10 [out]" C:/Users/huyi/Desktop/c626411e-531f-4dab-9a78-8103d92bbf1d.jpg
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9.3-win32 (GCC) 20200320
  configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf --disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, image2, from 'C:/Users/huyi/Desktop/1.jpg':
  Duration: 00:00:00.04, start: 0.000000, bitrate: 181106 kb/s
    Stream #0:0: Video: mjpeg (Progressive), yuvj444p(pc, bt470bg/unknown/unknown), 3840x2160, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
Press [q] to stop, [?] for help
[swscaler @ 000001d6cc29ad80] deprecated pixel format used, make sure you did set range correctly
Output #0, image2, to 'C:/Users/huyi/Desktop/c626411e-531f-4dab-9a78-8103d92bbf1d.jpg':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: mjpeg, yuvj420p(pc), 3840x2160, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 mjpeg
    Side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: N/A
[Parsed_movie_0 @ 000001d6cc40bd80] EOF timestamp not reliable
frame=    1 fps=0.0 q=11.4 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.176x    
video:455kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
C:/Users/huyi/Desktop/c626411e-531f-4dab-9a78-8103d92bbf1d.jpg

加文字水印效果

加logo效果

以上就是Python 实现给图片加文字或logo水印的详细内容,更多关于Python 图片水印的资料请关注脚本之家其它相关文章!

相关文章

  • Python中os模块的12种用法总结

    Python中os模块的12种用法总结

    OS ( Operating System 操作系统 ) 操作系统模块;它是属于python的标准库,常用于处理文件和目录(文件夹)的操作。本文为大家总结了这个模块的12种用法,希望有所帮助
    2022-08-08
  • Python的化简函数reduce()详解

    Python的化简函数reduce()详解

    这篇文章主要介绍了Python的化简函数reduce()详解,reduce()函数即为化简函数,它的执行过程为:每一次迭代,都将上一次的迭代结果与下一个元素一同传入二元func函数中去执行,需要的朋友可以参考下
    2023-12-12
  • Python tkinter模块中类继承的三种方式分析

    Python tkinter模块中类继承的三种方式分析

    这篇文章主要介绍了Python tkinter模块中类继承的三种方式,结合实例形式分析了三种继承方式的实现方法与相关注意事项,需要的朋友可以参考下
    2017-08-08
  • Python随机数模块详情

    Python随机数模块详情

    这篇文章主要介绍了Python随机数模块,随机数模块实现了各种分布的伪随机数生成器。对于整数,从范围中有统一的选择。 对于序列,存在随机元素的统一选择、用于生成列表的随机排列的函数、以及用于随机抽样而无需替换的函数,下文来看看详细内容,需要的朋友可以参考一下
    2021-11-11
  • numpy 计算两个数组重复程度的方法

    numpy 计算两个数组重复程度的方法

    今天小编就为大家分享一篇numpy 计算两个数组重复程度的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-11-11
  • Python使用requests模块发送http请求的方法介绍

    Python使用requests模块发送http请求的方法介绍

    Python Requests是一个 HTTP 库,它允许我们向 Web 服务器发送  HTTP 请求,并获取响应结果,本文将会详细介绍Python requests模块如何发送http请求,文中有相关的代码示例,需要的朋友可以参考下
    2023-06-06
  • Python内存管理器如何实现池化技术

    Python内存管理器如何实现池化技术

    Python中的内存管理是从三个方面来进行的,一对象的引用计数机制,二垃圾回收机制,三内存池机制,下面这篇文章主要给大家介绍了关于Python内存管理器如何实现池化技术的相关资料,需要的朋友可以参考下
    2022-05-05
  • opencv函数threshold、adaptiveThreshold、Otsu二值化的实现

    opencv函数threshold、adaptiveThreshold、Otsu二值化的实现

    这篇文章主要介绍了opencv函数threshold、adaptiveThreshold、Otsu二值化的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Python中的startswith和endswith函数使用实例

    Python中的startswith和endswith函数使用实例

    这篇文章主要介绍了Python中的startswith和endswith函数使用实例,特别是endswith函数,有了它,判断文件的扩展名、文件的类型在容易不过了,需要的朋友可以参考下
    2014-08-08
  • Python实现数通设备端口使用情况监控实例

    Python实现数通设备端口使用情况监控实例

    这篇文章主要介绍了Python实现数通设备端口使用情况监控的方法,涉及Python针对设备监控的操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07

最新评论