【问题标题】:How can I NOT save an image in PIL?如何不将图像保存在 PIL 中?
【发布时间】:2021-09-25 00:23:08
【问题描述】:

我只看到了将所有图像保存在 PIL 中的唯一方法,但 我不想全部保存。我正在制作一个不和谐的机器人,以在空间中发送带有用户个人资料图片的 meme。使用 Visual Studio 代码 有什么办法可以在我的笔记本电脑中保存一堆无用的图像?

#spongebob burning meme
@client.command(name= "spongebob_burn")
async def spongebob_burn(content, user: discord.member = None):
    if user is None:
        user = content.author
    
    spongebob_burn = Image.open("memes/Spongebobburn.jpeg")
    asset= user.avatar_url_as(size=128)
    data= BytesIO(await asset.read())
    pfp = Image.open(data)

    pfp = pfp.resize((74,74))
    spongebob_burn.paste(pfp, (22,45))
    spongebob_burn.save('sbb_new.jpeg')

    await content.send(file= discord.File("sbb_new.jpeg"))

我尝试删除保存行,因为这是我的第一直觉,但后来我过度考虑了它将如何发送以及发送什么

所以我立即尝试了 show 命令和其他我的大脑可以处理的方法

【问题讨论】:

  • 你试过删除spongebob_burn.save('sbb_new.jpeg')这行吗?
  • 那么我只是将 await content.send(file= discord.File("sbb_new.jpeg")) 更改为 await content.send(file= discord.File("memes/Spongebobburn.jpeg" ))```
  • 欢迎来到 Stack Overflow。用您自己的话来说,您认为哪部分代码负责保存图像? (提示:你的代码的哪一行有save这个词?)如果你不包括那个代码,你认为会发生什么?当你尝试这样做时发生了什么?
  • save() 命令替换为写入另一个BytesIO(就像您阅读它的位置)然后在该BytesIO 上写入getbuffer() 并发送结果而不是文件。
  • 不管怎样,如果你只是随机抓取一些代码并且不理解它们,那么你不应该尝试在这个级别编写项目。先学基础。如果您有一个更复杂的问题(例如,您希望对图像数据进行特定操作而不是保存它),那么您应该 a) 执行expected minimum research for your question(见How to Ask),如果你还有这个问题,就问这个问题。

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


【解决方案1】:

Mark Setchell 在 cmets 中已经回答了这个问题,但您似乎无法真正理解它,所以我会写一个答案。

您可以将图像保存到输出缓冲区,然后直接发送缓冲区。

from io import BytesIO

@client.command(name= "spongebob_burn")
async def spongebob_burn(content, user: discord.member = None):
    if user is None:
        user = content.author
    
    spongebob_burn = Image.open("memes/Spongebobburn.jpeg")
    asset = user.avatar_url_as(size=128)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)

    output_buffer = BytesIO()
    pfp = pfp.resize((74,74))
    spongebob_burn.paste(pfp, (22,45))
    spongebob_burn.save(output_buffer, "jpeg")

    await content.send(file=discord.File(fp=output_buffer, filename="sbb_new.jpeg"))

【讨论】:

  • 非常感谢,那天我只是没有用我的大脑T-T
猜你喜欢
  • 2013-01-05
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 2013-11-08
相关资源
最近更新 更多