-
-
Save edwardabraham/3392366 to your computer and use it in GitHub Desktop.
Implementation of a Django ImageField that converts all images to JPEG
This file contains hidden or 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 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