From 1e6070c1508995039ecbef1a11789c1da2f7477f Mon Sep 17 00:00:00 2001 From: Ryan Oldenburg Date: Tue, 14 Jun 2022 17:54:02 -0500 Subject: [PATCH] much faster toStraightAlpha --- src/pixie/internal.nim | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/pixie/internal.nim b/src/pixie/internal.nim index e5cb53e..3f309a6 100644 --- a/src/pixie/internal.nim +++ b/src/pixie/internal.nim @@ -81,16 +81,23 @@ proc fillUnsafe*( for j in i ..< start + len: data[j] = rgbx +const straightAlphaTable = block: + var table: array[256, array[256, uint8]] + for a in 0 ..< 256: + let multiplier = if a > 0: (255 / a.float32) else: 0 + for c in 0 ..< 256: + table[a][c] = min(round((c.float32 * multiplier)), 255).uint8 + table + proc toStraightAlpha*(data: var seq[ColorRGBA | ColorRGBX]) {.raises: [].} = ## Converts an image from premultiplied alpha to straight alpha. ## This is expensive for large images. - for c in data.mitems: - if c.a == 0 or c.a == 255: - continue - let multiplier = ((255 / c.a.float32) * 255).uint32 - c.r = ((c.r.uint32 * multiplier) div 255).uint8 - c.g = ((c.g.uint32 * multiplier) div 255).uint8 - c.b = ((c.b.uint32 * multiplier) div 255).uint8 + for i in 0 ..< data.len: + var c = data[i] + c.r = straightAlphaTable[c.a][c.r] + c.g = straightAlphaTable[c.a][c.g] + c.b = straightAlphaTable[c.a][c.b] + data[i] = c proc toPremultipliedAlpha*(data: var seq[ColorRGBA | ColorRGBX]) {.raises: [].} = ## Converts an image to premultiplied alpha from straight alpha.