Python中直接将截图转为Base64并存入字典的报错解决
问题:截图直接转Base64并存入字典报错解决
需求:截取屏幕后不保存图片,直接转换为Base64格式并存入字典。
原实现代码:
def screen(): global photo, numero_photo, photo_temporaire, photo_save time.sleep(3) position_screen = pyautogui.position() photo = pyautogui.screenshot(region = (position_screen[0] - 20, position_screen[1] - 20, 40, 40)) with open(photo, 'rb') as imagefile: format_byte = base64.b64encode(imagefile.read()) format_byte = str(format_byte) format_byte = format_byte.lstrip("b'") format_byte = format_byte.rstrip("'") photo_save.append(format_byte) print(photo_save)
执行时出现错误:
File "D:\Logiciel\Python\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "d:\Logiciel\programme\projet_bouclette\testbase64_7.py", line 23, in screen with open(photo, 'rb') as imagefile: TypeError: expected str, bytes or os.PathLike object, not Image
错误原因
pyautogui.screenshot()返回的是PIL Image对象,不是文件路径字符串。open()函数仅支持接收文件路径类参数,无法直接处理Image对象,因此触发类型错误。
修正方案
利用io.BytesIO将图片数据写入内存缓冲区,无需保存到本地文件,直接从缓冲区读取数据进行Base64编码,最后存入字典(原代码用列表存储,此处按需求调整为字典)。
修正后的代码:
import pyautogui import time import base64 from io import BytesIO # 初始化存储用的字典 photo_dict = {} def screen(): global photo_dict time.sleep(3) position_screen = pyautogui.position() # 截取指定区域的屏幕,得到Image对象 photo = pyautogui.screenshot(region=(position_screen[0]-20, position_screen[1]-20, 40, 40)) # 创建内存缓冲区 buffer = BytesIO() # 将图片保存到缓冲区,格式选PNG(也可用JPEG,需添加quality参数) photo.save(buffer, format='PNG') # 将缓冲区指针移到开头 buffer.seek(0) # 读取缓冲区数据并编码为Base64 format_byte = base64.b64encode(buffer.read()) # 转换为字符串(比手动裁剪更规范) base64_str = format_byte.decode('utf-8') # 将Base64字符串存入字典,用截图序号作为key示例 screenshot_id = len(photo_dict) + 1 photo_dict[f"screenshot_{screenshot_id}"] = base64_str print(photo_dict)
关键说明
- 使用
BytesIO实现纯内存操作,完全避免本地文件读写,符合需求 photo.save(buffer, format='PNG')指定图片格式,确保编码后的数据可正常还原为图片decode('utf-8')替代手动裁剪字符串,更简洁且不易出错- 采用字典存储,可通过自定义key(如截图时间、序号)快速检索对应Base64数据
内容的提问来源于stack exchange,提问作者bluehat
相关产品推荐
相关产品推荐

