python基础 Image模块

由一道题了解Imgae模块

第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果
在这里插入图片描述

Image

官方文档:https://pillow.readthedocs.io/en/stable/reference/Image.html
建议参考官方文档,如果不清楚可查看下面博主的文章,对比着来看,可以快速掌握创创建,存储,写字,图像重叠的等操作。

中文博客参考:
https://blog.csdn.net/icamera0/article/list/2
这位博主完整的讲了Image板块

图片的打开与显示

方法1

import PIL
from PIL import Image
# r是必须要用的
image = PIL.Image.open('D:\\PythonExcercise\\a1.jpg', mode='r')
image.show()

方法2

import PIL
import matplotlib.pyplot as plt
from PIL import Image

# r是必须要用的
image = PIL.Image.open('D:\\PythonExcercise\\a1.jpg', mode='r')
plt.figure('a1')
plt.imshow(image)
plt.show()
# 打印图片的相关信息
print(image.size)
print(image.mode)
print (image.format)

其他知识点

在Python的string前面加上‘r’, 是为了告诉编译器这个string是个raw string,不要转意backslash ‘’ 。 例如,\n 在raw string中,是两个字符,\和n, 而不会转意为换行符。由于正则表达式和 \ 会有冲突,因此,当一个字符串使用了正则表达式后,最好在前面加上’r’。

print('daad\tDA')
print(r'ADASD\t')
#################################
daad	DA
ADASD\t

完整的程序

from PIL import Image, ImageDraw, ImageFont

# get an image
base = Image.open(r'D:\PythonExcercise\a1.jpg').convert('RGBA')

# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255, 255, 255, 0))
txt.show()

# get a font
fnt = ImageFont.truetype(r'C:\Fonts\TrueType\euclidb.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
print(base.size)
# draw text, half opacity:半透明度,最后一个值是透明度
d.text((250, 10), "4", font=fnt, fill=(255, 0, 0, 128))
# 将两张图片合成在一起
out = Image.alpha_composite(base, txt)

out.show()
# 将文件储存起来,不能储存为jpg,会出现 cannot write mode RGBA as JPEG 的情况,因为RGBA中包括了透明度,转化为RGB就可以存储了,下面注释是转化的方法
# out_convert = out.convert('RGB')
# out_convert.save(r'D:\\PythonExcercise\\1.jpg')
out.save(r'D:\\PythonExcercise\\1.png')

在这里插入图片描述

发布了25 篇原创文章 · 获赞 2 · 访问量 833

猜你喜欢

转载自blog.csdn.net/Di_Panda/article/details/105166724
今日推荐