Django在不同的模型字段上保存图像

时间:2013-04-20 12:11:46

标签: python django django-signals django-models

我有一个名为Picture的模型。将图像上传到此模型后,它会在保存之前自动重新调整大小。

我的主要目标是将上传的图像重新调整为2个单独的图像。所以我可以将它用于不同的目的,如小图片和大图片。所以我为实现这个目标所做的就是创建另一个名为small的字段。代表小图片。

我的模型下面有两个函数叫做save​​和small。这些功能将自动重新调整图像大小。

我的计划是,当我将图像上传到模型时。我的保存功能会自动调整图像的大小并将其保存到图像文件夹中,但是如何让我的小功能从图像字段中获取该图像,以便它可以调整大小并将其保存到我的小字段中。

要求总和,它只是检索上传图像并在两个字段上调整图像大小。

class Picture(models.Model):
    user = models.ForeignKey(User)
    small = models.ImageField(upload_to="small/",blank=True,null=True)
    image = models.ImageField(upload_to="images/",blank=True)

    def save(self , force_insert=False,force_update=False):
        super (Picture,self).save(force_insert,force_update)

        pw = self.image.width
        ph = self.image.height
        mw = 500
        mh = 500

        if (pw > mw) or (ph > mh):
            filename = str(self.image.path)
            imageObj = img.open(filename)
            ratio = 1

            if ( pw > mw):
                ratio = mw / float(pw)
                pw = mw
                ph = int(math.floor(float(ph)* ratio))
            if ( ph > mh):
                ratio = ratio * ( mh /float(ph))
                ph = mh 
                pw = int(math.floor(float(ph)* ratio))

            imageObj = imageObj.resize((pw,ph),img.ANTIALIAS)
            imageObj.save(filename)

    def save(self , force_insert=False,force_update=False):
        super (Picture,self).save(force_insert,force_update)

        pw = self.image.width
        ph = self.image.height
        mw = 300
        mh = 300

        if (pw > mw) or (ph > mh):
            filename = str(self.image.path)
            imageObj = img.open(filename)
            ratio = 1

            if ( pw > mw):
                ratio = mw / float(pw)
                pw = mw
                ph = int(math.floor(float(ph)* ratio))
            if ( ph > mh):
                ratio = ratio * ( mh /float(ph))
                ph = mh 
                pw = int(math.floor(float(ph)* ratio))

            imageObj = imageObj.resize((pw,ph),img.ANTIALIAS)
            imageObj.save(filename)

如果这没有意义,请提醒我,以便我可以修改它

1 个答案:

答案 0 :(得分:1)

您可以创建自定义字段(继承ImageField)或创建pre_save信号来处理上传。

from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel


class MyModel(models.Model):
    # other fields
    image = MyCustomImageField(sizes=(('small', '300x300'), ('large', '500x500')))

信号

@receiver(pre_save, sender=MyModel)
def process_picture(sender, **kwargs):
    # do resizing and storage stuff

有关signals和自定义fields的详情。

A working example of a custom ImageField.