You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
911 B
32 lines
911 B
'''Images to and from sqlite''' |
|
import io, sqlite3 |
|
from PIL import Image |
|
|
|
#How to open a PIL image from a photostream |
|
with open('test-pattern.png', 'rb') as x: |
|
foto = x.read() |
|
|
|
fotostream = io.BytesIO(foto) |
|
image = Image.open(fotostream) |
|
|
|
#And now for sqlite3 |
|
|
|
conn = sqlite3.Connection('imagetest.db') |
|
cursor = conn.cursor() |
|
|
|
cursor.execute('CREATE TABLE IF NOT EXISTS images ("name" TEXT, "file" BLOB);') |
|
|
|
#make sure you insert the bytes from foto, not the io object |
|
cursor.execute('INSERT INTO images VALUES (?,?)', ('testimage', foto)) |
|
|
|
#retrieval |
|
cursor.execute('SELECT file from images') |
|
f2stream = io.BytesIO(cursor.fetchone()[0]) #fetchone returns a tuple |
|
f2img = Image.open(f2stream) |
|
f2img = f2img.convert('RGB') # original is RGBA and generates an error |
|
#see https://github.com/python-pillow/Pillow/issues/2609 |
|
f2img.save('test-pattern_converted.jpg') |
|
|
|
#and save that data |
|
conn.commit() |
|
conn.close()
|
|
|