About Adding White Background to Semi-transparent Images

PNG images with transparency contain color data for all pixels, including those that are partially or fully transparent, and if this transparency is lost during processing (like resizing), these previously invisible or semi-visible pixels can suddenly appear with unexpected colors, potentially resulting in black or other surprising hues in areas that were formerly transparent.

To make the resizing more predictable with django-imagekit, you can add a white background to all semi-transparent PNGs as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from imagekit import ImageSpec, register
from imagekit.processors import ResizeToFit
from PIL import Image

class AddWhiteBackground(object):
    def process(self, img):
        if img.mode in ("RGBA", "LA") or (
            img.mode == "P" and "transparency" in img.info
        ):
            background = Image.new("RGBA", img.size, (255, 255, 255, 255))
            background.paste(img, (0, 0), img)
            return background.convert("RGB")
        else:
            return img

class Banner728x90(ImageSpec):
    processors = [AddWhiteBackground(), ResizeToFit(442, 442)]
    format = "PNG"

register.generator("core:banner728x90", Banner728x90)

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 django-imagekit