public
Created

store multiple images in a single file using sqlite3 in Python

  • Download Gist
allessandro.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
import sqlite3
 
# support both Python 2.x and 3.x
try: buffer = buffer
except NameError:
buffer = lambda x: x # on Python 3.x 'rb' mode already returns what we need
 
def U(literal_string):
if hasattr(literal_string, 'decode'):
return literal_string.decode('utf-8') # source code encoding
return literal_string
 
# open db
conn = sqlite3.connect('images.db')
conn.execute('''create table if not exists images (
path unique not null,
image blob
)''')
 
def genimages():
"""Generate example images."""
for pngpath in glob.iglob(os.path.expanduser(U('~/Pictures/*.png'))):
with open(pngpath, 'rb') as f:
yield pngpath, buffer(f.read())
 
# insert images
with conn: # insert all or nothing
conn.executemany('insert into images(path,image) values(?, ?)', genimages())
 
# print image paths
for path, in conn.execute('select path from images'):
print(path)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.