Django Dynamic Logo Resizer with Background Fill
Working with logos sometimes requires the logo be a perfect square to work with the design style. The tricky part is that logos normally aren’t square at all, most are rectangular and no matter how you crop it, getting a perfect square normally ends up cutting part of the logo off. We also really don’t want to put the extra burden on the user to upload a perfect square or try to get them to use a standard image cropper to cut their own logo because it always comes out messy.
For a Django project I was working on, I wasn’t able to find any out-of-the-box solutions to do this, so I had to start with an existing image thumbnail generator and extend it to do the dynamic
How to Resize and Dynamically Background Fill
Below is an example LogoProcessor class that extends Django ImageKit‘s ImageSpec. The LogoProcessor class does two things to achieve our resized and background filled:
- Use Pill’s “getpixel” to detect the color of the first pixel. If it’s transparent it uses white.
- Passes the image background to ImageKit’s “mat_color” as a dynamic background fill for the new image.
from PIL import Image
from django.db import models
from django.conf import settings
from imagekit import ImageSpec, register
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFit
class LogoProcessor(ImageSpec):
format = 'JPEG'
options = {'quality': 90}
@property
def processors(self):
logoimage = self.source
image = Image.open(logoimage)
rgb_image = image.convert('RGB')
background_color = rgb_image.getpixel((1, 1))
if background_color == (0, 0, 0):
background_color = (255,255,255)
return [ResizeToFit(300, 300,mat_color=(background_color))]
register.generator('logo_processor', LogoProcessor)
class Company(models.Model):
logo = models.ImageField(
upload_to=settings.MEDIA_ROOT,default='')
logo_thumb = ImageSpecField(
source='logo',
id='logo_processor'
)
That’s it folks, hope this helps you work with logo uploads a little bit easier.