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.

This is normally what happens when we try to resize or crop a logo.


On the other hand, what we really want is a logo placed on a square canvas that matches the logos background color. Lets see what that looks like.


In this second example, we resized the logo first, and then filled the background of the canvas matching the color of the original logo image.

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:

  1. Use Pill’s “getpixel” to detect the color of the first pixel. If it’s transparent it uses white.
  2. Passes the image background to ImageKit’s “mat_color” as a dynamic background fill for the new image.

That’s it folks, hope this helps you work with logo uploads a little bit easier.