方法一:使用Pillow库



#Pillow库是Python中用于处理图像的常用库,它提供了一些方便的工具,可以很容易地添加水印。



#```python

from PIL import Image, ImageDraw, ImageFont



img = Image.open('image.jpg')



draw = ImageDraw.Draw(img)



text = '这是一段水印'



font = ImageFont.truetype('simsun.ttc', 30)



w, h = draw.textsize(text, font)



draw.text((img.width-w, img.height-h), text, font=font)



img.show()

#```



#方法二:使用opencv库



#OpenCV是一个计算机视觉库,它可以用于处理图像和视频。通过使用它的putText()函数,可以在图片上添加水印。


#
#```python

import cv2



img = cv2.imread('image.jpg')



text = '这是一段水印'



font_size = 1



font_thickness = 2



font = cv2.FONT_HERSHEY_SIMPLEX



text_width, text_height = cv2.getTextSize(text, font, font_size, font_thickness)[0]



text_x = img.shape[1] - text_width



text_y = img.shape[0] - text_height



cv2.putText(img, text, (text_x, text_y), font, font_size, (255, 255, 255), font_thickness)



cv2.imshow('image', img)



cv2.waitKey(0)

#```



#方法三:使用wand库



#Wand是一个Python库,是ImageMagick的C API的Python绑定。通过将文本渲染为图像,然后将文本图像合成到原始图像中,可以在图像上添加水印。


#
#```python

from wand.image import Image

from wand.color import Color

from wand.drawing import Drawing



with Image(filename='image.jpg') as img:

    with Color('white') as color:

        with Drawing() as draw:

            text = "这是一段水印"

            draw.font = 'simsun.ttc'

            draw.font_size = 30

            draw.fill_color = color

            draw.text(img.width - 200, img.height - 50, text)

            draw(img)

    img.save(filename='output.jpg')

```



以上三种方法均支持自动换行,只需要在绘制文本时判断文本的宽度,以此来决定换行位置。

(本文内容根据网络资料整理和来自用户投稿,出于传递更多信息之目的,不代表本站其观点和立场。也不对其真实性、可靠性承担任何法律责任,特此声明!)

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部