Skip to content

Instantly share code, notes, and snippets.

@edwardabraham
Forked from zmsmith/jpegfield.py
Created August 19, 2012 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardabraham/3392366 to your computer and use it in GitHub Desktop.
Save edwardabraham/3392366 to your computer and use it in GitHub Desktop.
Implementation of a Django ImageField that converts all images to JPEG
import os
from PIL import Image
import cStringIO
from django.core.files.base import ContentFile
from django.db.models import ImageField
from django.db.models.fields.files import ImageFieldFile
class JPEGImageFieldFile(ImageFieldFile):
def save(self, name, content, save=True):
if content:
image = Image.open(content)
if image.mode not in ('L', 'RGB'):
image = image.convert("RGB")
buf = cStringIO.StringIO()
image.save(buf, format="JPEG")
new_content_str = buf.getvalue()
content = ContentFile(new_content_str)
base, ext = os.path.splitext(name)
return super(JPEGImageFieldFile, self).save('%s.jpg' % base, content, save)
class JPEGImageField(ImageField):
"""
ImageField that converts all images to JPEG on save.
"""
attr_class = JPEGImageFieldFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment