【问题标题】:TypeError: memoryview: a bytes-like object is required, not 'JpegImageFile'TypeError:memoryview:需要一个类似字节的对象,而不是'JpegImageFile'
【发布时间】:2021-06-25 17:41:52
【问题描述】:

以下代码给了我一个错误:

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'

【问题讨论】:

    标签: python python-imaging-library


    【解决方案1】:

    正如错误消息所示,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()
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多