簡體   English   中英

Django - 旋轉圖像並保存

[英]Django - Rotate image and save

我想在 Django 中為圖像放置按鈕“向左旋轉”和“向右旋轉”。 這似乎很容易,但我已經失去了一些時間,嘗試了一些在 stackoverflow 上找到的解決方案,但還沒有結果。

我的模型有一個 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, '...',{...})

PS 為什么使用 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM