我如何通过 telepot Bot.sendPhoto(uid, photo) 将 BytesIO 图像上传到 Telegram?
How would I upload a BytesIO image to Telegram through telepot Bot.sendPhoto(uid, photo)?
所以,我希望能够通过 telepot 将我用二维码 class 生成的照片上传到 Telegram。这是我最初尝试过的代码!
img = qrcode.make(totp.provisioning_uri(settings.OTPNAME)) # This creates the raw image (of the qr code)
output = BytesIO() # This is a "file" written into memory
img.save(output, format="PNG") # This is saving the raw image (of the qr code) into the "file" in memory
bot.sendPhoto(uid, output) # This is sending the image file (in memory) to telegram!
如果我打算接受将照片保存到硬盘然后再上传的解决方案,我可以使用此代码上传!
imgTwo = open("image.png", 'rb') # So this works when combined with bot.sendPhoto(uid, imgTwo) # 'rb' means read + binary
bot.sendPhoto(uid, imgTwo)
我试过将 BytesIO 图像包装在 BufferedReader 中,甚至给它一个假名。
#output2 = BufferedReader(output)
#output.name = "fake.png"
#bot.sendPhoto(uid, ("fake.png", output))
这几天我一直在想办法弄清楚为什么我不能从记忆中上传照片。我查看了各种解决方案,例如 the fake name 解决方案!
Telegram 一直给我的错误是文件不能为空。将它保存到硬盘显示它不是空的,用我的身份验证应用程序扫描二维码显示二维码没有损坏!谢谢!
telepot.exception.TelegramError: ('Bad Request: file must be non-empty', 400, {'error_code': 400, 'ok': False, 'description': 'Bad Request: file must be non-empty'})
您必须在发送前将流指针归零:
img.save(output, format='PNG')
output.seek(0) # IMPORTANT!!!!!!!!!!!
bot.sendPhoto(uid, ('z.png', output))
每次要重新读取字节流的时候,记得把它指向开头。
所以,我希望能够通过 telepot 将我用二维码 class 生成的照片上传到 Telegram。这是我最初尝试过的代码!
img = qrcode.make(totp.provisioning_uri(settings.OTPNAME)) # This creates the raw image (of the qr code)
output = BytesIO() # This is a "file" written into memory
img.save(output, format="PNG") # This is saving the raw image (of the qr code) into the "file" in memory
bot.sendPhoto(uid, output) # This is sending the image file (in memory) to telegram!
如果我打算接受将照片保存到硬盘然后再上传的解决方案,我可以使用此代码上传!
imgTwo = open("image.png", 'rb') # So this works when combined with bot.sendPhoto(uid, imgTwo) # 'rb' means read + binary
bot.sendPhoto(uid, imgTwo)
我试过将 BytesIO 图像包装在 BufferedReader 中,甚至给它一个假名。
#output2 = BufferedReader(output)
#output.name = "fake.png"
#bot.sendPhoto(uid, ("fake.png", output))
这几天我一直在想办法弄清楚为什么我不能从记忆中上传照片。我查看了各种解决方案,例如 the fake name 解决方案!
Telegram 一直给我的错误是文件不能为空。将它保存到硬盘显示它不是空的,用我的身份验证应用程序扫描二维码显示二维码没有损坏!谢谢!
telepot.exception.TelegramError: ('Bad Request: file must be non-empty', 400, {'error_code': 400, 'ok': False, 'description': 'Bad Request: file must be non-empty'})
您必须在发送前将流指针归零:
img.save(output, format='PNG')
output.seek(0) # IMPORTANT!!!!!!!!!!!
bot.sendPhoto(uid, ('z.png', output))
每次要重新读取字节流的时候,记得把它指向开头。