Django - 旋转图像并保存

Django - Rotate image and save

我想在 django 中为图像添加按钮 "Rotate left" 和 "Rotate right"。 这似乎很容易,但我已经浪费了一些时间,尝试了一些在 Whosebug 上找到的解决方案,但还没有结果。

我的模型有一个 FileField:

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

我正在尝试这样的事情:

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

显然,它不起作用。我以为这会很简单,但我还不太了解 PIL 和 django 文件系统,我是 django 的新手。

抱歉我的英语不好。感谢您的帮助。

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。为什么使用 FileField 而不是 ImageField?

更新: 使用 python 3,我们可以这样做:

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