【问题标题】:How can I programatically save an Image to an ImageField using Django-Cumulus?如何使用 Django-Cumulus 以编程方式将图像保存到 ImageField?
【发布时间】:2012-06-15 08:22:06
【问题描述】:

我正在使用 Django-Cumulus 将图像存储到 Rackspace 的 Cloudfiles 平台。

我想动态地操作我的图像并将它们保存为我的模型的新 ImageField。例如,我有一个带有以下 ImageField 的 Photo 模型:image、thumb_256x256

在我的 Form 的 save() 方法中,我让用户指定裁剪位置(使用 JCrop)。

无论如何,我知道如何获取用户上传的现有图像文件。我也知道如何使用 PIL 进行操作。我遇到的问题是创建一个新的 Rackspace 文件并写入它。

我不断收到异常“NoSuchObject”。

下面是一些示例代码:

def save(self, commit=True):
    """ Override the Save method to create a thumbnail of the image. """
    m = super(PhotoUpdateForm, self).save(commit=False)

    image = Image.open(m.image.file)
    image.thumbnail((256,256), Image.ANTIALIAS)
    thumb_io = CloudFilesStorageFile(storage=CLOUDFILES_STORAGE, name='foo/bar/test.jpg')
    image.save(thumb_io.file, format='JPEG')

另外,一旦我谈到这一点 - 将此图像设置为模型的其他 ImageField 的最佳方法是什么? (在我的情况下为 m.thumb_256x256)

提前致谢!

更新:我正在使用的实际 Cloudfiles Django 应用程序的名称是“django-cumulus

【问题讨论】:

    标签: django rackspace-cloud django-models


    【解决方案1】:

    这是一个临时解决方案。我在正确设置新文件名时遇到问题。它只是将 _X 附加到文件名。例如,每当我保存新版本时,somefilename.jpg 就会变成 somefilename_1.jpg。

    这段代码有点难看,但确实可以完成工作。它会创建图像的裁剪版本,并在需要时生成缩略图。

    def save(self, commit=True):
        """ Override the Save method to create a thumbnail of the image. """
        m = super(PhotoUpdateForm, self).save(commit=False)
    
        # Cropped Version
        if set(('x1', 'x2', 'y1', 'y2')) <= set(self.cleaned_data):
            box = int(self.cleaned_data['x1']), \
                  int(self.cleaned_data['y1']), \
                  int(self.cleaned_data['x2']), \
                  int(self.cleaned_data['y2'])
            image = Image.open(m.image.file)
            image = image.crop(box)
            temp_file = NamedTemporaryFile(delete=True)
            image.save(temp_file, format="JPEG")
            m.image.save("image.jpg", File(temp_file))
            cropped = True # Let's rebuild the thumbnail
    
        # 256x256 Thumbnail
        if not m.thumb_256x256 or cropped:
            if not image:
                image = Image.open(m.image.file)
            image.thumbnail((256,256), Image.ANTIALIAS)
            temp_file = NamedTemporaryFile(delete=True)
            image.save(temp_file, format="JPEG")
            m.thumb_256x256.save("thumbnail.jpg", File(temp_file))
    
        if commit: m.save()
        return m
    

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 1970-01-01
      • 2012-02-08
      • 2015-03-30
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      相关资源
      最近更新 更多