Pillow库是一个非常好用的图像处理库。在Pillow库中,除了有二十多个模块,还支持非常多的插件。其中最常用的是Image模块中同名的Image类python显示图片,其他很多模块都是在Image模块的基础上对图像做进一步的特殊处理。
安装Pillow
pip install pillow
Pillow库安装成功后,导包时要用PIL来导入,而不能用pillow或Pillow。
打开本地图片
# coding=utf-8
from PIL import Image
image = Image.open("yazi.jpg")
image.show()
open(fp, mode=’r’): 打开一张图片,是Image模块中的函数。
如果图片与当前代码在同一目录下,可以只写图片的文件名,其他情况需要拼接图片的路径。mode默认为’r’python显示图片,也必须为’r’。
show(): 调用图片显示软件打开图片。
Image模块的常用属性
from PIL import Image
image = Image.open("yazi.jpg")
print('width: ', image.width)
print('height: ', image.height)
print('size: ', image.size)
print('mode: ', image.mode)
print('format: ', image.format)
print('category: ', image.category)
print('readonly: ', image.readonly)
print('info: ', image.info)
width属性表示图片的像素宽度,height属性表示图片的像素高度,
width和height组成了size属性,size是一个元组。
mode属性表示图片的模式,如RGBA,RGB,P,L等。
format属性表示图片的格式,格式一般与图片的后缀扩展名相关。
category属性表示图片的的类别。
readonly属性表述图片是否为只读,值为1或0,表示的是布尔值。
info属性表示图片的信息,是一个字典。
以下是使用 Pillow 库向图像添加标题的示例 Python 代码:
from PIL import Image, ImageDraw, ImageFont
# Open the image
image = Image.open("img_example.jpg")
# Define font and font size
font = ImageFont.truetype("Waree-Bold.ttf", 120)
# Define text
text = "Caption Example"
# Create a draw object
draw = ImageDraw.Draw(image)
# Calculate text size
text_size = draw.textsize(text, font=font)
# Calculate text position
x = image.width // 2 - text_size[0] // 2
y = image.height - 240 - text_size[1] // 2
# Draw text on image
draw.text((x, y), text, fill='white', font=font)
# Save the new image with the caption
image.save("img_example_with_caption.jpg")
此代码打开一个名为“img_example.jpg”的图像文件,在图像的底部中心添加标题“Caption Example”,并将新图像保存为“img_example_with_caption.jpg”。
您可以自定义字体、字体大小、文本、文本颜色和标题位置以满足您的特定需求。
要获取系统上的字体列表,请运行命令:locate .ttf
限时特惠:本站每日持续更新海量设计资源,一年会员只需29.9元,全站资源免费下载
站长微信:ziyuanshu688