From 9dd35c1dff4c941f3f4cb064748a6281cbb48734 Mon Sep 17 00:00:00 2001 From: "sashakoshka@tebibyte.media" Date: Tue, 10 Sep 2024 17:39:06 -0400 Subject: [PATCH] Add Premultiply and Unpremultiply functions --- image/color/color.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/image/color/color.go b/image/color/color.go index d763713..bfd5b39 100644 --- a/image/color/color.go +++ b/image/color/color.go @@ -18,3 +18,21 @@ func ToRGBA (c color.Color) color.RGBA { uint8(a >> 8), } } + +// Premultiply applies alpha-premultiplication that colors must apply as per +// color.Color.RGBA. This is an intrinsically lossy proccess. +func Premultiply (ur, ug, ub, ua uint32) (r, g, b, a uint32) { + return (ur * a) / 0xFFFF, + (ug * a) / 0xFFFF, + (ub * a) / 0xFFFF, + ua +} + +// Unpremultiply reverses alpha-premultiplication that colors must apply as per +// color.Color.RGBA. This may or may not return the precise original color. +func Unpremultiply (r, g, b, a uint32) (ur, ug, ub, ua uint32) { + return (r / a) * 0xFFFF, + (g / a) * 0xFFFF, + (b / a) * 0xFFFF, + a +}