如何将图像裁剪成某种形状,例如。在 Discord.py 中使用 Pillow 圈?

How to crop an image to a shape for eg. circle using Pillow in Discord.py?

如何将图像裁剪成某种形状,例如。在 Discord.py?

中使用 Pillow 画圈

我当前的代码:

@client.event
async def on_member_join(member : discord.Member):
    welcome = Image.open('Welcome.jpg')
    
    asset = member.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    pfp = pfp.resize((500, 500))
    welcome.paste(pfp, (657, 257))
    welcome.save("profile.jpg")

解决方案

  • 将pfp图像打开为numpy数组,转换为RGB
img = Image.open(data).convert("RGB")
npImage = np.array(img)
h,w = img.size
  • 创建与圆相同大小的 alpha 图层
alpha = Image.new('L', img.size,0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)
  • 将 alpha 图像转换为 numpy 数组
npAlpha=np.array(alpha)
  • 向 RGB 添加 alpha 层
npImage=np.dstack((npImage,npAlpha))
  • 使用 alpha 保存图像!
Image.fromarray(npImage).save('result.png')

例子

import numpy as np
from PIL import Image, ImageDraw

@client.event
async def on_member_join(member : discord.Member):
    welcome = Image.open('Welcome.jpg')
    
    asset = member.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    img=Image.open(data).convert("RGB")
    npImage=np.array(img)
    h,w=img.size
    
    alpha = Image.new('L', img.size,0)
    draw = ImageDraw.Draw(alpha)
    draw.pieslice([0,0,h,w],0,360,fill=255)
    npAlpha=np.array(alpha)
    npImage=np.dstack((npImage,npAlpha))
    pfp = Image.fromarray(npImage)
    welcome.paste(pfp, (657, 257))
    welcome.save("profile.jpg")