如何在TelegramBotAPI中处理photo对象实现QR码解密
问题根因
Telegram Bot API 返回的 message.photo 是不同分辨率的 PhotoSize 对象列表,本身不包含图片二进制数据,也没有 save 方法,因此你原先的写法无法正常执行。
解决步骤
- 从
message.photo列表中选择对应分辨率的图片对象,通常取列表最后一个元素即为最高清版本 - 调用
bot.get_file()方法获取图片的文件路径,再调用download()方法将二进制内容写入 BytesIO 对象 - 由于 OpenCV 的
detectAndDecode()方法不直接读取 BytesIO 流,需要先将二进制内容转换为 numpy 数组再传入解码
修正后可运行代码
首先确保导入所需依赖:
import numpy as np import cv2 from io import BytesIO
解密功能实现代码:
# 绑定处理图片类型消息的处理器,分步交互场景可自行调整触发逻辑 @bot.message_handler(content_types=['photo']) def decrypting(message): detector = cv2.QRCodeDetector() # 取最高清的图片版本 photo_size = message.photo[-1] # 获取文件信息 file_info = bot.get_file(photo_size.file_id) # 下载图片二进制到BytesIO,无需存本地磁盘 bio = BytesIO() bot.download_file(file_info.file_path, bio) bio.seek(0) # 将二进制转为OpenCV可读取的numpy数组 img_array = np.asarray(bytearray(bio.read()), dtype=np.uint8) img = cv2.imdecode(img_array, cv2.IMREAD_COLOR) # 解码QR码 data, bbox, _ = detector.detectAndDecode(img) # 处理返回结果 if data: bot.send_message(message.chat.id, f'QR code data: \n\n{data}') else: bot.send_message(message.chat.id, '未检测到QR码,请确认图片内容后重试')
注意事项
如果解码成功率低,可以尝试先对图片做灰度化、二值化预处理再传入解码。
内容的提问来源于stack exchange,提问作者Valeriy Leonov
相关产品推荐
相关产品推荐

