Resize image according to other model fields

Viewed 131

How do I use the value of other model fields in some field? I want to resize an image to the width and height specified in their respective fields:

class MyImage(models.Model):
    name = models.CharField(max_length=128, blank=False)
    width = models.PositiveIntegerField(blank=False)  #--->
    height = models.PositiveIntegerField(blank=False)  #--->
    new_image = ProcessedImageField(processors=[ResizeToFill(500, 500)],  #<---
                                    format='JPEG',
                                    options={'quality': 60})

I have to to swap first 500 into value from variable width and and second 500 into variable height. The field ProcessedImageField is from a package django-imagekit that I am using.

2 Answers

As described in the django-imagekit documentation on Specs That Change you can write a separate class for the ImageSpec provide the processors attribute as a property to dynamically get the proccessors, register this image spec and provide it's id to your ProcessedImageField to achieve your purpose:

from django.db import models
from imagekit import ImageSpec, register
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
from imagekit.utils import get_field_info

class YourImage(ImageSpec):
    format = 'JPEG'
    options = {'quality': 60}

    @property
    def processors(self):
        model, field_name = get_field_info(self.source)
        return [ResizeToFill(model.width, model.height)]

register.generator('your_app:your_image', YourImage)


class MyImage(models.Model):
    name = models.CharField(max_length=128, blank=False)
    width = models.PositiveIntegerField(blank=False)
    height = models.PositiveIntegerField(blank=False)
    new_image = ProcessedImageField(spec_id='your_app:your_image')
Related