首页 文章

使用ImageField保存图像后修改图像

提问于
浏览
0

我完全迷失了如何在保存之后修改图像 . 我有一个模特:

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

图像上传得很好 . 我已经把这个问题看了一堆,我发现了一些片段和类似的问题,但我仍然非常困惑 . 是的,我已经对这种确切的混淆/问题进行了大量搜索 .

有什么方法我可以:

  • 访问已保存的图像目录 .

  • 找到按名称/目录上传的图像 .

  • 在图像上运行我的modify_image(filename) .

  • 将修改后的图像保存在其他目录中 .

我已经阅读了Django网站上有关管理文件的文档,我对StackOverflow进行了一段时间的尝试,尝试了不同的解决方案 . 我所要求的只是对上述内容采取直截了当的方法 . 如果太麻烦你甚至不需要给我看任何代码 . 我只是不知所措,我不知道我现在在做什么,所以解决方案的一些算法布局会很棒 . 谢谢 .


Here's my current attempt:

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')

哪里不对了?

2 回答

  • 0

    你真正需要的是当一个对象即将保存到DB时调用的 hook . 我要做的是将所有图像处理逻辑放在模型的函数中 . 但是,这会降低您网站的用户体验 . 在那种情况下,我建议写的是celery task . 更好的是你可以运行periodic task

  • 0

    我已经解决了自己的问题 . 原来我错误地覆盖了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')
    

    The problem was:

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

    So I changed it to:

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

    它完全符合我现在想做的事情 .

相关问题