Django - Rotate image and save

2019-07-19 11:21发布

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.

1条回答
Viruses.
2楼-- · 2019-07-19 11:41
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?

查看更多
登录 后发表回答