'How do you crop an image to be circular with pillow in discord.py?
so I'm trying to make a "wanted" command where my bot places the user's avatar image over a wanted poster. I was able to get the command to work but I'm having some trouble trying to crop their avatar to be circular. Here is my code:
@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"))
Here is the error I am getting:
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'```
Solution 1:[1]
It's complaining because a Discord Asset object does not have the attribute size according to the docs.
What you want to use instead is the PIL Image object which has the size attribute you are looking for. This can be done by slightly changing your code:
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cho'Gath |
