pillow使用之:圆形头像

说在最前

在使用pillow制作海报的过程中,最经常用的场景:

  1. 文字居中(地址)
  2. 粘贴一张带透明背景的png图片(地址)
  3. 画一个圆形的用户头像(地址)

准备

  • 环境
    • linux/windows
    • python 3.6.*
  • 依赖
    • Pillow(使用前请先使用 pip install Pillow 安装依赖)

讲解

本文讲解第3个,画一个圆形的用户头像,实际上为前面一篇的应用,我们直接通过代码讲解

# 导入需要的包
from PIL import Image, ImageDraw
import os

# 背景尺寸
bg_size = (750, 1334)
# 生成一张尺寸为 750x1334 背景色为白色的图片
bg = Image.new('RGB', bg_size, color=(255,255,0))

# 头像尺寸
avatar_size = (200, 200)
# 头像路径
avatar_path = os.path.join('.', 'imgs', 'avatar.jpeg')
# 加载头像文件到 avatar
avatar = Image.open(avatar_path)
# 把头像的尺寸设置成我们需要的大小
avatar = avatar.resize(avatar_size)

# 新建一个蒙板图, 注意必须是 RGBA 模式
mask = Image.new('RGBA', avatar_size, color=(0,0,0,0))
# 画一个圆
mask_draw = ImageDraw.Draw(mask)
mask_draw.ellipse((0,0, avatar_size[0], avatar_size[1]), fill=(0,0,0,255))

# 计算头像位置
x, y = int((bg_size[0]-avatar_size[0])/2), int((bg_size[1]-avatar_size[1])/2)
# box 为头像在 bg 中的位置
# box(x1, y1, x2, y2)
# x1,y1 为头像左上角的位置
# x2,y2 为头像右下角的位置
box = (x, y, (x + avatar_size[0]), (y + avatar_size[1]))
# 以下使用到paste(img, box=None, mask=None)方法
#   img 为要粘贴的图片对你
#   box 为图片 头像在 bg 中的位置
#   mask 为蒙板,原理同 ps, 只显示 mask 中 Alpha 通道值大于等于1的部分
bg.paste(avatar, box, mask)

# 要保存图片的路径
img_path = os.path.join('.', 'output', 'round_avatar.jpg')
# 保存图片
bg.save(img_path)
print('保存成功 at {}'.format(img_path))

# GUI环境可以使用下面方式直接预览
# bg.show()

运行效果

round_avatar.jpg

说明

图片来自网络,如有侵权,请与作者联系
转载请注明出处,谢谢

完整demo地址:https://github.com/1lin24/pillow_demo

你可能感兴趣的:(pillow使用之:圆形头像)