Skip to content

Instantly share code, notes, and snippets.

@zmsmith
Created January 11, 2011 03:59
Show Gist options
  • Save zmsmith/773999 to your computer and use it in GitHub Desktop.
Save zmsmith/773999 to your computer and use it in GitHub Desktop.
ImageField that converts all images to JPEG on save.
import Image
import cStringIO
import os
from django.core.files.base import ContentFile
from django.db.models import ImageField
from django.db.models.fields.files import ImageFieldFile
class JPEGFieldFile(ImageFieldFile):
"""
ImageFieldFile subclass for JPEGField
"""
def save(self, name, content, save=True):
image = Image.open(content)
buf = cStringIO.StringIO()
image.save(buf, format="JPEG")
new_content_str = buf.getvalue()
new_content = ContentFile(new_content_str)
old_name = os.path.splitext(name)[0]
name = "%s%s" % (old_name,'.jpg')
return super(JPEGImageFieldFile, self).save(name, new_content, save)
class JPEGImageField(ImageField):
"""
ImageField that converts all images to JPEG on save.
"""
attr_class = JPEGFieldFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment