简体   繁体   中英

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 results yet.

My model has a FileField:

class MyModel(models.Model):
    ...
    file = models.FileField('file', upload_to=path_and_rename, null=True)
    ...

I'm trying something like this:

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

    photo_new = StringIO.StringIO(myModel.file.read())
    image = Image.open(photo_new)
    image = image.rotate(-90)

    image_file = StringIO.StringIO()
    image.save(image_file, 'JPEG')

    f = open(myModel.file.path, 'wb')
    f.write(##what should be here? Can i write the file content this way?##) 
    f.close()


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

Obviously, it's not working. I thought that this would be simple, but i don't understand PIL and django file system well yet, i'm new in django.

Sorry for my bad english. I appreciate any help.

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, '...',{...})

PS Why do you use FileField instead of ImageField?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM