Skip to content

Instantly share code, notes, and snippets.

@rominf
Last active August 8, 2020 14:30
Show Gist options
  • Save rominf/6792358340ecfbd1b2a7 to your computer and use it in GitHub Desktop.
Save rominf/6792358340ecfbd1b2a7 to your computer and use it in GitHub Desktop.
PostgreSQL function to crop images (uses plpythonu and python PIL)
CREATE OR REPLACE FUNCTION crop(image bytea, rect box)
RETURNS bytea
LANGUAGE plpythonu
AS $function$
if ('io' in SD) and ('StringIO' in SD) and ('Image' in SD):
io = SD['io']
StringIO = SD['StringIO']
Image = SD['Image']
else:
import io, StringIO
from PIL import Image
SD['io'] = io
SD['StringIO'] = StringIO
SD['Image'] = Image
rect_list = [int(x) for x in rect.strip().replace('(', '').replace(')', '').split(',')]
rect_list = rect_list[2:] + rect_list[:2]
im = Image.open(io.BytesIO(image))
im = im.crop(rect_list)
f = StringIO.StringIO()
im.save(f, 'jpeg')
f.seek(0)
return f.read()
$function$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment