如何限制图像到ASCII转换器一次输出的字符数,使其以不协调的方式输出,每条消息限制2000个字符

2024-10-03 21:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像到ASCII的转换器,与discord机器人一起工作,这样人们可以向它发送一个图像,它下载图像并将其转换为ASCII,然后发送回给他们,但是由于discord将消息限制为每个2000个字符,所以它经常无法生成合理大小的图像

我使用this教程转换图像,我相信这行代码:

asciiImage = "\n".join(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))

是我需要修复的一个,我相信它将图像的每一行连接到一个基于newWidth变量的换行符,当你给它图像时,你输入这个变量。如何限制它只添加行,直到下一行超过2000行,输出该行(或将其添加到列表),然后重复,直到完成图像

抱歉,如果这有点混乱


Tags: 代码in图像消息forascii机器人教程
1条回答
网友
1楼 · 发布于 2024-10-03 21:33:19

您可以在for循环中对其进行迭代,并跟踪字符串的当前大小。如果添加下一行会使它太大,请发送它,重置字符串并继续

然后,如果需要,发送字符串的最后一部分(不会在for循环中自动发送)

注意:下面的示例假设您有一个channel要向其发送消息,将其替换为ctxuser或任何您的意图Channel只是为了这个例子

# Entire ascii image as a list of lines (not joined into one string)
asciiImage = list(newImageData[i:(i + newWidth)] for i in range(0, pixelCount, newWidth))

# String to send
send_str = ""

for line in asciiImage:
    # Adding this line would make it too big
    # 1998 = 2000 - 2, 2 characters for the newline (\n) that would be added
    if len(send_str) + len(line) > 1998:
        # Send the current part
        await channel.send(send_str)
        # Reset the string
        send_str = ""

    # Add this line to the string
    send_str += line + "\n"
    
# Send the remaining part
if send_str:
    await channel.send(send_str)

相关问题 更多 >