Skip to main content

Premultiplied alpha

There are two ways to store a color with an alpha. Straight alpha keeps the color as it is and the opacity beside it: a half-transparent red is (255, 0, 0, 128). Premultiplied alpha stores the color already multiplied by the opacity: the same pixel is (128, 0, 0, 128). Files, and every Image, use straight alpha. Rasterizers, the programs that draw vector graphics (Cairo, Skia, Qt, novasvg), draw into premultiplied buffers, because blending is cheaper there: one multiply and one add per channel.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
badge = stb.Image.open("badge.png") # straight alpha, as every Image
w = badge.width

# The first pixel of the soft rim: neither opaque nor invisible.
straight = badge.tobytes()
index = next(i for i in range(0, len(straight), 4) if 0 < straight[i + 3] < 255)
r, g, b, a = straight[index : index + 4]
print(f"pixel ({index // 4 % w}, {index // 4 // w}), straight: ({r}, {g}, {b}, {a})")

# Premultiplied: each color is multiplied by alpha / 255 (and truncated), so the pixel is already "what it adds".
premultiplied = badge.premultiplied()
pm = premultiplied.tobytes()[index : index + 4]
print(f"premultiplied: ({pm[0]}, {pm[1]}, {pm[2]}, {pm[3]})")
print("equals color * alpha / 255:", "yes" if tuple(pm[:3]) == (r * a // 255, g * a // 255, b * a // 255) else "no")

# Back again. It is exact where alpha is 255, and not where alpha is small: the colors lost their low bits.
back = premultiplied.unpremultiplied().tobytes()
worst, at = 0, 0
for i in range(0, len(straight), 4):
error = max(abs(back[i + c] - straight[i + c]) for c in range(3))
if error > worst:
worst, at = error, straight[i + 3]
print(f"round trip: the worst color error is {worst}, at alpha {at}")

# Reading premultiplied bytes as if they were straight is a classic mistake: the rim turns dark.
badge.flatten((255, 255, 255)).write("out/correct.png")
premultiplied.flatten((255, 255, 255)).write("out/misread.png")

# PremultipliedImage is a separate type, one 32-bit word per pixel: no blend, no encoder, no resize, so it cannot be misread.
p = stb.PremultipliedImage.from_image(badge)
print(f"premultiplied image: {p.width} x {p.height}, rows {p.stride} bytes apart")
print("to_image() gives the same pixels as unpremultiplied():", "yes" if p.to_image().tobytes() == premultiplied.unpremultiplied().tobytes() else "no")
Output
pixel (58, 0), straight: (230, 57, 70, 3)
premultiplied: (2, 0, 0, 3)
equals color * alpha / 255: yes
round trip: the worst color error is 103, at alpha 2
premultiplied image: 160 x 160, rows 640 bytes apart
to_image() gives the same pixels as unpremultiplied(): yes
straight, flattened on white
straight, flattened on white
premultiplied read as straight
premultiplied read as straight

Converting​

premultiplied() makes a new image whose colors are multiplied by alpha (c * a / 255, truncated) and unpremultiplied() goes back (c * 255 / a, and zeros where alpha is 0). Only RGBA and gray-with-alpha pictures change; the other formats come back as a copy. The conversion is not exact: where alpha is small, the multiplication throws low bits of the color away, and they cannot be got back. The example prints the worst error of the whole picture and the alpha it happened at: the rim, not the solid disc.

The mistake​

An Image does not remember that it was premultiplied, and blend, the encoders and resize all expect straight alpha. If you write premultiplied pixels to a PNG, or blend them, the soft edge comes out too dark, as in the second picture: the color was already multiplied once and is multiplied again. Call unpremultiplied() before using the result as an ordinary image.

The type that cannot be misread​

PremultipliedImage is for the buffers that rasterizers draw into. It is a separate type on purpose: one 32-bit word 0xAARRGGBB per pixel, rows stride bytes apart, and none of the straight-alpha calls (no blend, no encoder, no resize), so it cannot be used by mistake. from_image converts in (a gray or RGB picture is taken as opaque RGBA) and to_image converts back to straight RGBA.

numpy.asarray(p) gives a (height, width) view of 32-bit words, with no copy, for a rasterizer written in NumPy. Keep p alive while you use it.

API at a glance​

To premultipliedimg.premultiplied()
Back to straightimg.unpremultiplied()
The separate typestb.PremultipliedImage.from_image(img)
Back to an Imagep.to_image()
Its sizep.width, p.height, p.stride