2013-06-04 41 views
0

我完全失去了在保存图像后应如何修改图像的问题。我有一个模型:使用ImageField保存图像后修改图像

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

该图像上传就好了。我已经查找了这个问题,我发现了一些片段和类似的问题,但我仍然非常困惑。是的,我经历了一系列关于这种混乱/问题的搜索。

有什么办法,我可以只:

  1. 访问已保存的图像目录。
  2. 找到名称/目录上传的图片。
  3. 在图像上运行我的modify_image(文件名)。
  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') 

什么不对?

+1

下面是保存后调整图像大小的示例:http://djangosnippets.org/snippets/1100/ –

回答

0

我已经解决了我自己的问题。原来我被重写保存()不正确:

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) 

这不正是我希望现在就做。

0

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

+0

这完全不能帮助我,对不起。 –