如何将 base64 解码为图像 discord.py 并发送

How to decode a base64 to an image discord.py and send it

所以我发现了这个 API,它有助于图像处理。它以 base64 格式给出结果。我搜索了很多但找不到如何将 base64 解码为图像。这是代码:-

@bot.command()
async def image(ctx, method=None):
  params = {'method': method, 'img1': 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png'}
  header = {"Authorization": "mykey"}
  async with aiohttp.ClientSession(headers=header) as session:
    async with session.post(f'https://api.pgamerx.com/v5/canvas', params=params) as resp:
      res = await resp.json()
      data = res[0]["base64"]
      print(data)

我打印数据以获取 base64 字符串,它非常庞大,粘贴时差点让我的电脑崩溃。任何帮助将不胜感激。

(注)代码没有问题,一切正常

import io, base64  # Add these imports to the top of the file

@bot.command()
async def image(ctx, method=None):
  params = {'method': method, 'img1': 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png'}
  header = {"Authorization": "mykey"}
  async with aiohttp.ClientSession(headers=header) as session:
    async with session.post(f'https://api.pgamerx.com/v5/canvas', params=params) as resp:
      res = await resp.json()
      data = res[0]["base64"]
      print(data)
      file = discord.File(io.BytesIO(base64.b64decode(data)))
      await ctx.send(file=file)

这里使用 base64.b64decode to decode the base64 encoded string, then wraps the result in a bytesio 以便 discord.File

可以读取