spectre
spectre

Reputation: 11

TypeError: memoryview: a bytes-like object is required, not 'JpegImageFile'

The following code is giving me an error:

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()

The error is:

TypeError: memoryview: a bytes-like object is required, not 'JpegImageFile'

Upvotes: 1

Views: 8493

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55600

As the error message suggests, a memoryview expects to receives raw bytes. To get the bytes that make up the image, do this:

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()

Or more succintly:

with io.BytesIO() as buf:
    img.save(buf, 'jpeg')
    image_bytes = buf.getvalue()

Upvotes: 5

Related Questions