Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.