【问题标题】:Django - Rotate image and saveDjango - 旋转图像并保存
【发布时间】:2016-05-11 00:02:19
【问题描述】:

我想在 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 的新手。

对不起,我的英语不好。感谢您的帮助。

【问题讨论】:

    标签: python django python-imaging-library


    【解决方案1】:
    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?

    【讨论】:

    • 有时我需要在此字段上传其他类型的文件(例如 PDF)。非常感谢您的回答!
    • myModel.file.save(image.file.path, ContentFile(rotated_photo.getvalue())) 出现错误。 AttributeError,显然 PIL 图像上不存在“文件”字段
    • 适用于:myModel.file._get_path()
    【解决方案2】:

    更新: 使用 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-06-09
      相关资源
      最近更新 更多