Skip to content

Instantly share code, notes, and snippets.

@rominf
Last active April 3, 2024 08:04
Show Gist options
  • Save rominf/f614b77053e2d0aba253 to your computer and use it in GitHub Desktop.
Save rominf/f614b77053e2d0aba253 to your computer and use it in GitHub Desktop.
PostgreSQL function to resize images (uses plpythonu and python PIL)
CREATE OR REPLACE FUNCTION resize(image bytea, h integer, w integer)
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
im = Image.open(io.BytesIO(image))
im.thumbnail((h, w), Image.ANTIALIAS)
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