Skip to main content
 首页 » 编程设计

python之Django之旋转图像并保存

2025年04月02日29dflying

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

附言为什么使用 FileField 而不是 ImageField?