加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Python3 图片添加水印

发布时间:2021-05-21 04:53:02 所属栏目:大数据 来源: https://blog.csdn.net/yilovex
导读:PIL 图像库 使用 pip install PIL 时报如下错误: Collecting PILCould not find a version that satisfies the requirement PIL (from versions: )No matching distribution found for PIL 实际上需要安装的是 Pillow sudo pip install Pillow 示例代码: #

PIL 图像库

使用 pip install PIL 时报如下错误:

Collecting PIL
Could not find a version that satisfies the requirement PIL (from versions: )
No matching distribution found for PIL

实际上需要安装的是Pillow

sudo pip install Pillow

示例代码:

# coding:utf-8

from PIL import Image,ImageDraw,ImageFont


def add_text_to_image(image,text):
    font = ImageFont.truetype('C:WindowsFontsSTXINGKA.TTF',36)

    # 添加背景
    new_img = Image.new('RGBA',(image.size[0] * 3,image.size[1] * 3),(0,0))
    new_img.paste(image,image.size)

    # 添加水印
    font_len = len(text)
    rgba_image = new_img.convert('RGBA')
    text_overlay = Image.new('RGBA',rgba_image.size,(255,255,0))
    image_draw = ImageDraw.Draw(text_overlay)

    for i in range(0,rgba_image.size[0],font_len*40+100):
        for j in range(0,rgba_image.size[1],200):
            image_draw.text((i,j),text,font=font,fill=(0,50))
    text_overlay = text_overlay.rotate(-45)
    image_with_text = Image.alpha_composite(rgba_image,text_overlay)

    # 裁切图片
    image_with_text = image_with_text.crop((image.size[0],image.size[1],image.size[0] * 2,image.size[1] * 2))
    return image_with_text


if __name__ == '__main__':
    img = Image.open("test.jpg")
    im_after = add_text_to_image(img,'石家庄')
    im_after.save('水印.png')

Python3 无法将模式 RGBA 写为 JPEG

JPG 不支持透明度, RGBA 表示红色、绿色、蓝色 Alpha 是透明度

你需要丢弃 Alpha 通道或保存为支持透明度的东西比如 PNG

图像类有一个方法转换,可以用来将 RGBA 转换为 RBG 之后你就可以使用 JPG

im = Image.open("audacIoUs.png")
rgb_im = im.convert('RGB')
rgb_im.save('audacIoUs.jpg')

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读