Skip to content

Commit

Permalink
Fix un-pre-mul alpha calculations
Browse files Browse the repository at this point in the history
Fixes #1970
  • Loading branch information
andydotxyz committed Feb 18, 2021
1 parent d2e7244 commit 8a67b5f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 11 deletions.
28 changes: 17 additions & 11 deletions dialog/color.go
Expand Up @@ -245,17 +245,7 @@ func colorToRGBA(c color.Color) (r, g, b, a int) {
b = int(col.B)
a = int(col.A)
default:
red, green, blue, alpha := c.RGBA()
if alpha != 0 && alpha != 1 {
red /= alpha
green /= alpha
blue /= alpha
}
// Convert from range 0-65535 to range 0-255
r = int(float64(red) / 255.0)
g = int(float64(green) / 255.0)
b = int(float64(blue) / 255.0)
a = int(float64(alpha) / 255.0)
r, g, b, a = unmultiplyAlpha(c)
}
return
}
Expand Down Expand Up @@ -354,3 +344,19 @@ func hueToChannel(h, v1, v2 float64) float64 {
}
return v2
}

func unmultiplyAlpha(c color.Color) (r, g, b, a int) {
red, green, blue, alpha := c.RGBA()
if alpha != 0 && alpha != 0xffff {
ratio := float64(alpha) / 0xffff
red = uint32(float64(red) / ratio)
green = uint32(float64(green) / ratio)
blue = uint32(float64(blue) / ratio)
}
// Convert from range 0-65535 to range 0-255
r = int(red >> 8)
g = int(green >> 8)
b = int(blue >> 8)
a = int(alpha >> 8)
return
}
18 changes: 18 additions & 0 deletions dialog/color_test.go
Expand Up @@ -380,3 +380,21 @@ func Test_hueToChannel(t *testing.T) {
})
}
}

func Test_UnmultiplyAlpha(t *testing.T) {
c := color.RGBA{R: 100, G: 100, B: 100, A: 100}
r, g, b, a := unmultiplyAlpha(c)

assert.Equal(t, 255, r)
assert.Equal(t, 255, g)
assert.Equal(t, 255, b)
assert.Equal(t, 100, a)

c = color.RGBA{R: 100, G: 100, B: 100, A: 255}
r, g, b, a = unmultiplyAlpha(c)

assert.Equal(t, 100, r)
assert.Equal(t, 100, g)
assert.Equal(t, 100, b)
assert.Equal(t, 255, a)
}

0 comments on commit 8a67b5f

Please sign in to comment.