Database Reference
In-Depth Information
Thinking
out
of
the
"SQL
database
server" box
We'll wrap up the chapter on PL/Python with a couple of sample PL/Pythonu functions
for doing some things you would not usually consider doing inside the database func-
tion or trigger.
Generating thumbnails when saving images
Our first example uses Python's powerful Python Imaging Library ( PIL ) module to
generate thumbnails of uploaded photos. For ease of interfacing with various client
libraries, this program takes the incoming image data as a base-64 encoded string:
CREATE FUNCTION
save_image_with_thumbnail(image64 text)
RETURNS int
AS $$
import Image, cStringIO
size = (64,64) # thumbnail size
# convert base64 encoded text to binary image
data
raw_image_data = image64.decode('base64')
# create a pseudo-file to read image from
infile = cStringIO.StringIO(raw_image_data)
pil_img = Image.open(infile)
pil_img.thumbnail(size, Image.ANTIALIAS)
# create a stream to write the thumbnail to
outfile = cStringIO.StringIO()
pil_img.save(outfile, 'JPEG')
raw_thumbnail = outfile.getvalue()
# store result into database and return row id
q = plpy.prepare('''
Search WWH ::




Custom Search