You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中如何将API返回的base64内容解码为图片并发送

解决方案

卡顿问题处理

打印base64导致设备卡顿属于正常情况:base64编码后的体积是原二进制文件的4/3,高清处理后图片的base64字符串长度可达数十万甚至数百万级别,直接完整打印到终端会占用极高的内存和渲染资源。你可以仅打印前缀校验数据是否正常获取即可:

# 只打印前50位字符,避免卡顿
print(data[:50])

base64转图片实现

你可以直接用Python内置模块完成解码,无需写入本地磁盘即可直接在bot中发送图片,完整修改后的代码如下:

import base64
import io
from discord import 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"]
            # 处理base64可能带的媒体头前缀,比如data:image/png;base64,
            if 'base64,' in data:
                data = data.split('base64,')[1]
            # 解码base64为二进制数据
            img_bytes = base64.b64decode(data)
            # 封装为BytesIO文件对象,可直接用于发送
            img_file = io.BytesIO(img_bytes)
            # 发送图片,指定文件名
            await ctx.send(file=File(fp=img_file, filename='processed.png'))

如果需要将图片保存到本地,只需要在解码完成后写入文件即可:

with open('processed.png', 'wb') as f:
    f.write(img_bytes)

内容的提问来源于stack exchange,提问作者ChaoticNebula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:39:00