Skip to content Skip to sidebar Skip to footer

Django - Rotate Image And Save

I want to put buttons 'Rotate left' and 'Rotate right' for images in django. It seems to be easy, but i've lost some time, tryed some solutions found on stackoverflow and no result

Solution 1:

from django.core.files.base import ContentFile

def rotateLeft(request,id):
    myModel = myModel.objects.get(pk=id)

    original_photo = StringIO.StringIO(myModel.file.read())
    rotated_photo = StringIO.StringIO()

    image = Image.open(original_photo)
    image = image.rotate(-90)
    image.save(rotated_photo, 'JPEG')

    myModel.file.save(image.file.path, ContentFile(rotated_photo.getvalue()))
    myModel.save()

    return render(request, '...',{...})

P.S. Why do you use FileField instead of ImageField?

Solution 2:

UPDATE: Using python 3, we can do like this:

    my_model = MyModel.objects.get(pk=kwargs['id_my_model'])

    original_photo = io.BytesIO(my_model.file.read())
    rotated_photo = io.BytesIO()

    image = Image.open(original_photo)
    image = image.rotate(-90, expand=1)
    image.save(rotated_photo, 'JPEG')

    my_model.file.save(my_model.file.path, ContentFile(rotated_photo.getvalue()))
    my_model.save()

Post a Comment for "Django - Rotate Image And Save"