Book Image

PostgreSQL Server Programming - Second Edition

Book Image

PostgreSQL Server Programming - Second Edition

Overview of this book

Table of Contents (21 chapters)
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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 function 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 Base64 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...