Merge pull request #534 from homm/fix-getcolor-rgba

Fix ImageColor.getcolor
This commit is contained in:
Alex Clark ☺ 2014-03-17 10:20:40 -04:00
commit da3ab720f4
2 changed files with 26 additions and 9 deletions

View File

@ -117,17 +117,18 @@ def getcolor(color, mode):
:return: ``(red, green, blue)`` :return: ``(red, green, blue)``
""" """
# same as getrgb, but converts the result to the given mode # same as getrgb, but converts the result to the given mode
color = getrgb(color) color, alpha = getrgb(color), 255
if mode == "RGB": if len(color) == 4:
return color color, alpha = color[0:3], color[3]
if mode == "RGBA":
if len(color) == 3:
color = (color + (255,))
r, g, b, a = color
return r, g, b, a
if Image.getmodebase(mode) == "L": if Image.getmodebase(mode) == "L":
r, g, b = color r, g, b = color
return (r*299 + g*587 + b*114)//1000 color = (r*299 + g*587 + b*114)//1000
if mode[-1] == 'A':
return (color, alpha)
else:
if mode[-1] == 'A':
return color + (alpha,)
return color return color
colormap = { colormap = {

View File

@ -26,9 +26,25 @@ for color in list(ImageColor.colormap.keys()):
assert_equal((0, 0, 0), ImageColor.getcolor("black", "RGB")) assert_equal((0, 0, 0), ImageColor.getcolor("black", "RGB"))
assert_equal((255, 255, 255), ImageColor.getcolor("white", "RGB")) assert_equal((255, 255, 255), ImageColor.getcolor("white", "RGB"))
assert_equal((0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB"))
Image.new("RGB", (1, 1), "white")
assert_equal((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
assert_equal((255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
assert_equal((0, 255, 115, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA"))
Image.new("RGBA", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "L")) assert_equal(0, ImageColor.getcolor("black", "L"))
assert_equal(255, ImageColor.getcolor("white", "L")) assert_equal(255, ImageColor.getcolor("white", "L"))
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
Image.new("L", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "1")) assert_equal(0, ImageColor.getcolor("black", "1"))
assert_equal(255, ImageColor.getcolor("white", "1")) assert_equal(255, ImageColor.getcolor("white", "1"))
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
assert_equal((0, 255), ImageColor.getcolor("black", "LA"))
assert_equal((255, 255), ImageColor.getcolor("white", "LA"))
assert_equal((162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
Image.new("LA", (1, 1), "white")