【问题标题】:Modifying an image after saving it with ImageField使用 ImageField 保存后修改图像
【发布时间】:2013-06-04 04:37:14
【问题描述】:

我完全不知道如何在保存图像后对其进行修改。我有一个模型:

class Pic(models.Model):
    imgfile = FaceChopField(upload_to='img/%m/%d')

图片上传就好了。我查了很多这个问题,发现了很多sn-ps和类似的问题,但我仍然非常困惑。是的,我已经就这种确切的混淆/问题进行了一系列搜索。

有什么办法可以:

  1. 访问保存的图像目录。
  2. 找到按名称/目录上传的图片。
  3. 在图像上运行我的 modify_image(filename)。
  4. 将修改后的图像保存在其他目录中。

我已经阅读了 Django 站点上有关管理文件的文档,并且我已经研究了 StackOverflow 一段时间,尝试了不同的解决方案。我所要求的也许是对上述内容的直接方法。如果太麻烦的话,你甚至不需要给我看任何代码。我只是不知所措,我不知道此时我在做什么,所以解决方案的一些算法布局会很棒。谢谢。


这是我目前的尝试:

class FaceChopFieldFile(ImageFieldFile):
    def __init__(self, *args, **kwargs):
        super(FaceChopFieldFile, self).__init__(*args, **kwargs)

    def save(self):
        super(FaceChopFieldFile, self).save()
        image_content = facechop(self.path) #my image modification function

        self.storage.save(self.path, image_content)


class FaceChopField(ImageField):
    attr_class = FaceChopFieldFile    


class Pic(models.Model): 
    imgfile =  FaceChopField(upload_to='img/%m/%d')

有什么问题吗?

【问题讨论】:

标签: django django-models


【解决方案1】:

你真正需要的是一个hook,当一个对象即将被保存到数据库时调用它。我要做的是在函数中包含所有图像处理逻辑,覆盖您的模型的save method。但是,这会减慢您网站的用户体验。在这种情况下,我建议写celery task。更好的是你可以运行periodic task

【讨论】:

  • 这对我没有帮助,抱歉。
【解决方案2】:

我已经解决了我自己的问题。结果我错误地覆盖了 save():

class FaceChopFieldFile(ImageFieldFile):
    def __init__(self, *args, **kwargs):
        super(FaceChopFieldFile, self).__init__(*args, **kwargs)

    def save(self, name, content, save=True):
        super(FaceChopFieldFile, self).save(name, content, save)
        image_content = facechop(self.path) #my image modification function

        self.storage.save(self.path, image_content)


class FaceChopField(ImageField):
    attr_class = FaceChopFieldFile



class Pic(models.Model): 
    imgfile =  FaceChopField(upload_to='img/%m/%d')

问题是:

def save(self):
    super(FaceChopFieldFile, self).save()

所以我改成了:

def save(self, name, content, save=True):
            super(FaceChopFieldFile, self).save(name, content, save)

这正是我现在想要它做的事情。

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2016-04-23
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多