python - TypeError:memoryview:需要一个类似字节的对象,而不是'JpegImageFile'
问题描述
以下代码给了我一个错误:
def save(self):
self.filePath, _ = QFileDialog.getOpenFileName(self, "Open File ", "", "JPEG(*.JPEG *.jpeg *.JPG *.jpg)")
img =Image.open(self.filePath)
conn.execute("INSERT INTO DriverInfo(driverImg)VALUES(?)", repr(memoryview(img)))
conn.commit()
错误是:
TypeError: memoryview: a bytes-like object is required, not 'JpegImageFile'
解决方案
正如错误消息所示,memoryview期望接收原始字节。要获取构成图像的字节,请执行以下操作:
from io import BytesIO
img = Image.open('1x1.jpg')
# Create a buffer to hold the bytes
buf = BytesIO()
# Save the image as jpeg to the buffer
img.save(buf, 'jpeg')
# Rewind the buffer's file pointer
buf.seek(0)
# Read the bytes from the buffer
image_bytes = buf.read()
# Close the buffer
buf.close()
或者更简洁地说:
with io.BytesIO() as buf:
img.save(buf, 'jpeg')
image_bytes = buf.getvalue()
推荐阅读
- python - 将平均值添加到包含不同列中的值的每一行
- javascript - TypeError: Object(...) is not a function ReactJS + Recoil
- c++ - pcap_set_rfmon 成功但实际上不起作用
- javascript - 2021 年 7 月之后从 Chrome 扩展程序访问 Google 文档的内容
- mysql - 数据库结构帮助
- amazon-s3 - Pyspark 从 S3 存储桶读取 csv 文件:AnalysisException:路径不存在
- c# - 雪花:是否有一个查询会返回我在创建表时设置的数据类型?int 到 int,而不是 int 到数字?
- android - 如何通过android中的Web服务器进行面部认证登录?
- python - 是否可以使用 OpenID 登录网站,该网站不提供客户端 ID 和客户端密码以及 Python 中的请求?
- javascript - 从 Vue.js 开始,什么都没有显示