Linux加载png背景图片,pillow使用之:粘贴一张带透明背景的png图片

说在最前

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

文字居中(地址)

粘贴一张带透明背景的png图片(地址)

画一个圆形的用户头像(地址)

准备

环境

linux/windows

python 3.6.*

依赖

Pillow(使用前请先使用 pip install Pillow 安装依赖)

讲解

本文讲解第2个,粘贴一张带透明背景的png图片,我们直接通过代码讲解

# 导入需要的包

from PIL import Image, ImageDraw

import os

# 背景尺寸

bg_size = (750, 1334)

# 生成一张尺寸为 750x1334 背景色为白色的图片

bg = Image.new('RGBA', bg_size, color=(255,255,0,255))

# 要粘贴的图片尺寸

fruit_size = (120, 100)

# 图片地址

fruit_path = os.path.join('.', 'imgs', 'fruits.png')

# 加载png图片,并手动转为 rgba 模式

fruit = Image.open(fruit_path).convert('RGBA')

# 计算图片位置

# fruit_box 为头像在 bg 中的位置

# fruit_box(x1, y1, x2, y2)

# x1,y1 为头像左上角的位置

# x2,y2 为头像右下角的位置

x, y = int((bg_size[0]-fruit_size[0])/2), int((bg_size[1]-fruit_size[1])/2)

fruit_box = (x, y, (x + fruit_size[0]), (y + fruit_size[1]))

# 将图片设置为我们需要的大小

fruit = fruit.resize(fruit_size)

# box 为头像在 bg 中的位置

# box(x1, y1, x2, y2)

# x1,y1 为头像左上角的位置

# x2,y2 为头像右下角的位置

bg.paste(fruit, fruit_box, fruit)

# 要保存图片的路径

img_path = os.path.join('.', 'output', 'png_paste.png')

# 保存图片

bg.save(img_path)

print('保存成功 at {}'.format(img_path))

# GUI环境可以使用下面方式直接预览

# bg.show()

运行效果

8ea7f1057875

png_paste.png

说明

图片来自网络,如有侵权,请与作者联系

转载请注明出处,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值