News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

2024-11(7)

Add text watermarks to pictures through Python's PIL library

posted on 2023-05-03 20:57     read(766)     comment(0)     like(9)     collect(4)



foreword

Hello everyone, I am Kongkong star. In this article, I will share with you how to add text watermark to pictures through Python's PIL library .


1. What is PIL?

PIL is the abbreviation of Python Imaging Library, which is one of the commonly used image processing libraries in Python language. It provides a wealth of image processing functions, including operations such as opening, saving, cropping, rotating, and scaling, and supports multiple image formats.

2. Install PIL

pip install pillow

3. Check the PIL version

pip show pillow

Name: Pillow
Version: 9.4.0
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: aclark@python-pillow.org
License: HPND
Requires:
Required-by: image, imageio, matplotlib, pytesseract, wordcloud

Fourth, use the PIL library to add text watermarks to pictures

1. Import library

from PIL import Image, ImageDraw, ImageFont

2. Open the picture file

local = '/Users/kkstar/Downloads/video/pic/'
image = Image.open(local+"demo.jpg")

3. Create a new Draw object

draw = ImageDraw.Draw(image)

4. Set watermark text, font, size

text = '@空空star'
font = ImageFont.truetype('STHeitiMedium.ttc', size=80)

5. Set watermark color

5.1 Set color by name

# 通过名称设置颜色-黄色
color = 'yellow'

5.2 Set color by RGB value

# 通过RGB值设置颜色-红色
color = (255, 0, 0)

5.3 Set color by RGBA value

# 通过RGBA值设置颜色-白色
color = (255,255,255,0)

5.4 Set color by hexadecimal

# 通过十六进制设置颜色-绿色
color = '#6FE000'

6. Get the size of the watermark text

text_width, text_height = draw.textsize(text, font)

7. Set the watermark position

7.1 upper left

x = 30
y = 30

7.2 Bottom right

x = image.width-text_width-30
y = image.height-text_height-30

Adjust the x and y values ​​at other positions. This 30 is set by me like this, you can also adjust it according to your own preferences.

8. Add watermark

draw.text((x, y), text, font=font, fill=color)

9. Save the picture

image.save(local+'image_with_watermark.jpg')

Summarize



Category of website: technical article > Blog

Author:kkkkkkkkkkdsdsd

link:http://www.pythonblackhole.com/blog/article/293/9475b96c291b1bc3c37f/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

9 0
collect article
collected

Comment content: (supports up to 255 characters)