İbrahim İpek
İbrahim İpek

Reputation: 184

How to add transparency (alpha) as percent in PIL.ImageColor.getcolor?

I have a function that returns,

return "rgba({}%, {}%, {}%, {}%)".format(Percent_1, Percent_2, Percent_3, Alpha)

When i put this value in PIL.ImageColor.getcolor as in,

I.putpixel((J, K), ImageColor.getcolor(RGBAColorFunction(J, K), "RGBA"))

I get the following error (for example):

ValueError: unknown color specifier: 'rgba(30%, 50%, 70%, 50%)'

I have looked to docs but there was no detailed info, neither good examples. How to solve this?

Upvotes: 2

Views: 619

Answers (1)

Vasu Deo.S
Vasu Deo.S

Reputation: 1850

Pass the pixel values without the % sign. Change the returns statement from

return "rgba({}%, {}%, {}%, {}%)".format(Percent_1, Percent_2, Percent_3, Alpha)

to

return "rgba({}, {}, {}, {})".format(Percent_1, Percent_2, Percent_3, Alpha)

I saw the documentation of ImageColor module, and it states that values could be given in percentage, but that is not true.

Upon doing Source Code Analysis of the function getcolor() it turns out that it calls getrgb() in order to get the values of color as a tuple, from the provided string. And getrgb() uses Regex for pattern matching the string in order to extract values off from it.

REGEX USED FOR MATCHING RGBA:-

rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$

it turns out that percentages % are not taken into account in this regex, therefore tuple of format equivalent to rgba(x, x, x, x) (where x is an integer) are only allowed.

P.S.:- If you still want to send the output in percentages, you could simply do the math on the values before returning them.

Upvotes: 2

Related Questions