为什么这个 PIL 生成的图像奇怪地扭曲了? [英] Why is this PIL-Generated Image weirdly distorted?

查看:75
本文介绍了为什么这个 PIL 生成的图像奇怪地扭曲了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个 discord.py 机器人并制作一个命令,该命令发送带有目标头像的图像和在其顶部拍打的手部图像.然而,它只是发送一个没有头像的非常奇怪的拍手图片.我的代码:

I am trying to make a discord.py bot and make a command that sends an image with the target's avatar and a slapping hand image on top of it. However, it is just sending a really weird hand slap picture without the avatar. My Code:

@commands.command()
async def avatar(self, ctx, user : discord.Member):
    """User Avatar Testing"""
    filename = f"{user.name}#{user.discriminator}.png"
    await user.avatar_url.save(filename)
    fileslap = Image.open("assets/slap.png", "r")

    im = Image.open(filename).convert("RGB")

    resized_im = im.resize((128,  128))

    img_w, img_h = fileslap.size
    bg_w, bg_h = resized_im.size

    offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
    resized_im.paste(fileslap, offset)
    resized_im.save(f"temp/resized_{filename}")

    file = discord.File(fp=f"temp/resized_{filename}")

    await ctx.send(file=file)
    os.remove(f"temp/resized_{filename}")

实际用户头像:

它将实际用户的个人资料图片保存为:

What it saves the actual user's Profile Picture as:

输出:

推荐答案

我是这样制作 slap 命令的.如果您想参考,它可以工作并提供适当的输出.

I made the slap command like this. It works and gives proper output if you want to refer.

@commands.command()
    async def slap(self,ctx, user : discord.Member =None):
        try:
            if not user:
                    user=ctx.author
            await ctx.send("Just slapped :wave: "+user.mention)
            response = requests.get(user.avatar_url)
            image_bytes = io.BytesIO(response.content)
            person = Image.open(image_bytes)
            slap = Image.open(".\cogs\slapping\slap.jpg")
            person_res=person.resize((100,100))
            area=(100,100,200,200)
            slap.paste(person_res, area)
            slap.save(".\\cogs\\slapping\\"+str(user.id)+".jpg")
            with open(".\\cogs\\slapping\\"+str(user.id)+".jpg", 'rb') as f:
                picture = discord.File(f)
                await ctx.send(file=picture)
            os.remove(".\\cogs\\slapping\\"+str(user.id)+".jpg")
        except Exception as e:
            print(e)

它生成的输出是:

您需要在 cogs 文件夹中有一个 slapping 文件夹,您可以在其中存储名为slap.jpg"的图片.如果需要修改,只需更改代码中的目录即可.

You will need a slapping folder in the cogs folder where you can store a picture named "slap.jpg". Just change the directory in the code if you want some modification.

这篇关于为什么这个 PIL 生成的图像奇怪地扭曲了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆