【问题标题】:How do you crop an image to be circular with pillow in discord.py?如何在 discord.py 中将图像裁剪为带有枕头的圆形?
【发布时间】:2021-02-01 15:03:01
【问题描述】:

所以我试图发出一个“通缉”命令,让我的机器人将用户的头像图像放在通缉的海报上。我能够让命令工作,但我在尝试将他们的头像裁剪为圆形时遇到了一些麻烦。这是我的代码:

@bot.command(aliases=['Wanted'])
async def wanted(ctx,*, user: discord.Member = None):
  async with ctx.typing():
    if user == None:
        user = ctx.author

    wanted = Image.open("wanted.png")
    
    asset = user.avatar_url_as(size=128)

    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    bigsize = (asset.size[0] * 3, asset.size[1] * 3)
    mask = Image.new('L', bigsize, 0)
    draw = ImageDraw.Draw(mask) 
    draw.ellipse((0, 0) + bigsize, fill=255)
    mask = mask.resize(asset.size, Image.ANTIALIAS)
    asset.putalpha(mask)

    pfp = pfp.resize((682,682))
    output = ImageOps.fit(asset, mask.size, centering=(0.5, 0.5))

    output.putalpha(mask)
    
    wanted.paste(pfp,(280,480))

    wanted.save("profile.png")

    await ctx.send(file=discord.File("profile.png"))

这是我得到的错误:


Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Asset' object has no attribute 'size'```

【问题讨论】:

    标签: python discord python-imaging-library discord.py image-manipulation


    【解决方案1】:

    因为 Discord Asset 对象没有 size according to the docs 属性而抱怨。

    您想要使用的是 PIL Image object,它具有您正在寻找的 size 属性。这可以通过稍微更改您的代码来完成:

    asset = user.avatar_url_as(size=128)
    
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    # Instead of using asset.size, we use pfp.size.  pfp is a PIL Image object
    # that has the size attribute.
    bigsize = (pfp.size[0] * 3, pfp.size[1] * 3)
    

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 2021-02-08
      • 1970-01-01
      • 2012-10-08
      • 2016-05-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多