美文网首页
pillow使用之:粘贴一张带透明背景的png图片

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

作者: 1lin24 | 来源:发表于2019-05-23 15:10 被阅读0次

    说在最前

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

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

    准备

    • 环境
      • 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()
    

    运行效果

    png_paste.png

    说明

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

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

    相关文章

      网友评论

          本文标题:pillow使用之:粘贴一张带透明背景的png图片

          本文链接:https://www.haomeiwen.com/subject/frtbzqtx.html