1.效果展示
2. 素材
tree.png
penguin.jpg
3. 代码
from PIL import Image
# 读取tree图片
tree = Image.open("tree.png")
# 读取tree图片的长宽
size_x, size_y = tree.size
# 读取自己的头像图片
head_portrait = Image.open("penguin.jpg")
# 读取自己头像图片的长宽
size_w, size_h = head_portrait.size
# 根据我们的需要裁剪tree,得到square图片
square = tree.crop((80, 45, size_y+50, size_y-100))
# 将square图片设置为与自己头像大小一样大小
square = square.resize((size_w, size_h))
# 设置渐进
for i in range(size_w):
for j in range(size_h):
color = square.getpixel((i, j))
alpha = 255 - i//3
if alpha < 0:
alpha = 0
color = color[:-1] + (alpha,)
square.putpixel((i, j), color)
# 粘贴到头像并保存
head_portrait.paste(square, (0, 0), square)
head_portrait.save('半透明渐变头像.png')
4.注意事项
crop函数自己根据图像截取能得到不同效果。
作者:Beyong
出处:Beyong博客
github地址:https://github.com/beyong2019
本博客中未标明转载的文章归作者Beyong有,欢迎转载,但未经作者同意必须保留此段声明,且在文章明显位置给出原文连接,否则保留追究法律责任的权利。