Skip to content

Instantly share code, notes, and snippets.

@zmsmith
Created June 20, 2011 21:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zmsmith/1036692 to your computer and use it in GitHub Desktop.
Save zmsmith/1036692 to your computer and use it in GitHub Desktop.
Implementation of a Django ImageField that converts all images to JPEG
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)
return super(JPEGImageFieldFile, self).save(name, content, save)
class JPEGImageField(ImageField):
"""
ImageField that converts all images to JPEG on save.
"""
attr_class = JPEGImageFieldFile
from django import models
class SimpleModel(models.Model):
the_field = models.FileField()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment