[Django]-Django – Rotate image and save

2👍

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?

1👍

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()

Leave a comment