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

目录
  • 前言
  • 环境依赖
  • 代码
  • 验证一下
  • 执行结果

前言

本文提供给图片添加文字或者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 图片水印的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python如何为图片添加水印

    添加水印的主要目的是为了版权保护,使自己的图像不被抄袭或者恶意转载.网上有很多制作水印的工具,本帖介绍怎么使用Python-Pillow库给图片添加水印. 使用ImageMagick添加图片水印-Linux 添加文本水印 在图片右下角添加文字: from PILimport Image, ImageDraw, ImageFont # 指定要使用的字体和大小:/Library/Fonts/是macOS字体目录:Linux的字体目录是/usr/share/fonts/ font = ImageFon

  • 2行Python实现给图片加水印效果

    目录 前言 filestools库介绍 一行代码给图片加水印 总结 前言 版权相当重要,对于某张图片,可能是你精心制作的思维导图,或者你精心设计的某个logo.你可能花费好多时间来弄,最后却被别人直接搬运过去使用,好气哦! 基于此,本文我就带着大家学学如何给你的图片加水印,仅需要2行Python代码,任何人都可以学会. filestools库介绍 今天给大家介绍的Python库,叫做filestools,由小小明开发,直接使用如下命令,安装后使用. pip install filestools

  • python使用PIL模块实现给图片打水印的方法

    本文实例讲述了python使用PIL模块实现给图片打水印的方法.分享给大家供大家参考.具体实现方法如下: import Image, ImageEnhance def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im

  • python实现图片加文字水印OPenCV和PIL库

    目录 一:openCV给图片添加水印 二:使用PIL给图片添加水印 在python中我们可以使用openCV给图片添加水印,这里注意openCV无法添加汉字水印,添加汉字水印上可使用PIL库给图片添加水印 一:openCV给图片添加水印 1:安装openCV pip install opencv-python 2:使用openCV给图片添加水印实例: # -*- coding: utf-8 -*- import cv2 # 载入突破 img = cv2.imread('test.jpg') #

  • Python 使用 Pillow 模块给图片添加文字水印的方法

    像微博一类的平台上传图片时,平台都会添加一个水印,宣誓着对图片的所有权,我们自己的博客平台也可以给自己的图片添加上水印. 还是用 Pillow 模块来实现 先来看一个简单的例子 >>> from PIL import Image >>> from PIL import ImageDraw >>> >>> image = Image.open('/Users/wxnacy/Downloads/vm-error1.png') >&g

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

    目录 前言 环境依赖 代码 验证一下 执行结果 前言 本文提供给图片添加文字或者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 : i

  • 随时给自己贴的图片加文字的php水印

    随时给自己贴的图片加文字  <?  Header( "Content-type: image/jpeg");  function makethumb($srcFile,$text,$size=12,$R=0,$G=0,$B=0) {  if(!$text){  $text='welcome xs.net.ru xayle';  $size=20;  $R=255;  }  $data = GetImageSize($srcFile,&$info);  switch ($d

  • Android自定义实现图片加文字功能

    Android自定义实现图片加文字功能 分四步来写: 1,组合控件的xml; 2,自定义组合控件的属性; 3,自定义继承组合布局的class类,实现带两参数的构造器; 4,在xml中展示组合控件. 具体实现过程: 一.组合控件的xml 我接触的有两种方式,一种是普通的Activity的xml:一种是父节点为merge的xml.我项目中用的是第一种,但个人感觉第二种好,因为第一种多了相对或者绝对布局层. 我写的 custom_pictext.xml <?xml version="1.0&qu

  • php给图片加文字水印

    注释非常的详细了,这里就不多废话了 <?php /*给图片加文字水印的方法*/ $dst_path = 'http://f4.topitme.com/4/15/11/1166351597fe111154l.jpg'; $dst = imagecreatefromstring(file_get_contents($dst_path)); /*imagecreatefromstring()--从字符串中的图像流新建一个图像,返回一个图像标示符,其表达了从给定字符串得来的图像 图像格式将自动监测,只要

  • 在Python 中实现图片加框和加字的方法

    第一步:安装opencv-python rpm -ivh opencn-python-2.4.5-3.el7.ppc64le.rpm 第二步:引用cv2 import cv2 第三步:读入图片,必须是全路径 im = cv2.imread(filename) 第四步:设置需要画框的左上角与右下角的坐标,必须是整数 sx1, sx2, sy1, sy2 cv2.rectangle(im,(int(sx1),int(sy1)),(int(sx2),int(sy2)),(0,255,0),3) 函数参

  • Python实现识别图片为文字的示例代码

    目录 1.环境准备 2.业务实现 3.效果展示 本来想着做一个将图片识别为文字的小功能,本想到Google上面第一页全是各种收费平台的广告. 这些平台提供的基本都是让我们通过调用相关的三方接口实现的,本着坚决不想花一分钱的态度,在论坛找有没有可以免费解决的方案. 果然,有大佬早就做出开源框架pytesseract,差点让我损失了一笔巨款,哈哈~ 这次只为实现将图片识别为文字的业务功能,就不使用PyQt5做页面应用了.后面若是需要做成UI应用朋友比较多,我有时间会将这个小工具封装开发成一个PyQ5

  • 利用Python自带PIL库扩展图片大小给图片加文字描述的方法示例

    前言 最近的一个项目中需要在图片上添加文字,使用了OpenCV,结果发现利用opencv给图像添加文字有局限.可利用的字体类型比较少,需要安装Freetype扩展,比较复杂.而且不能用putText函数输出中文,否则就会出现乱码的情况.只好选择使用Python PIL函数库对照片进行处理,利用Python自带的PIL库扩展图片大小给图片加上文字描述,大多都是库函数调用,只是给定图片宽度后计算文字所需行数的代码需要写. 代码比较丑,but it works. 代码示例 #!/usr/bin/env

  • Android给图片加文字和图片水印实例代码

    我们在做项目的时候有时候需要给图片添加水印,水寒今天就遇到了这样的问题,所以搞了一个工具类,贴出来大家直接调用就行. /** * 图片工具类 * @author 水寒 * */ public class ImageUtil { /** * 设置水印图片在左上角 * @param Context * @param src * @param watermark * @param paddingLeft * @param paddingTop * @return */ public static Bi

随机推荐