Created
January 11, 2011 03:59
-
-
Save zmsmith/773999 to your computer and use it in GitHub Desktop.
ImageField that converts all images to JPEG on save.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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