dropout
dropout

Reputation: 89

Why fillcolors get scrumbled in python imaging library?

I'm trying to draw shapes with colors, with this extremely simple piece of code:

from PIL import Image, ImageDraw

img = Image.new( "RGB", (256,256))
draw = ImageDraw.Draw(img)

draw.rectangle( [(0,0),(256,128)], fill="#FF0000" )
draw.rectangle( [(0,128),(256,256)], fill=0xFF0000 )

# img.show()
img.save("test.png")

My first rectangle will be RED, but the second is BLUE. I know values are not the same: one is a string, the other one is an integer, but obviously the program should interpret it the same way shouldn't it? Or am I overlooking some straightforward thing? I'm drawing gradients with integers and found this strange behaviour. Thanks for any guidance.

Upvotes: 2

Views: 1504

Answers (2)

jsbueno
jsbueno

Reputation: 110271

Well, since you did not get the same colors, obviously the library us not interpreting them the same way.

The first form you have a color as it is specified in HTML and CSS names - a string, and you could have used the words "red" and "blue" just as you used "#ff0000" - On the second form you are actually passing it an integer number that will represent the color. Since it shows red instead of blue, the byte order is reversed when you input colors in this format - just try 0x0000FF instead. (i.e. it takes BGR instead of RGB)

If you are using numbers rather than strings, note that you can sent a 3-tuple with the RGB values as well, like in draw.rectangle( [(0,128),(256,256)], fill=(255, 0,0) ) (doing it this way also uses RGB)

"reality is what you get away with"

Upvotes: 1

StefanE
StefanE

Reputation: 7630

It does not support it. Here is what is supported:

Colour Names

In PIL 1.1.4 and later, you can also use string constants when drawing in "RGB" images. PIL supports the following string formats:

Hexadecimal color specifiers, given as "#rgb" or "#rrggbb". For example, "#ff0000" specifies pure red.

RGB functions, given as "rgb(red, green, blue)" where the colour values are integers in the range 0 to 255. Alternatively, the color values can be given as three percentages (0% to 100%). For example, "rgb(255,0,0)" and "rgb(100%,0%,0%)" both specify pure red.

Hue-Saturation-Lightness (HSL) functions, given as "hsl(hue, saturation%, lightness%)" where hue is the colour given as an angle between 0 and 360 (red=0, green=120, blue=240), saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%). For example, "hsl(0,100%,50%)" is pure red.

Common HTML colour names. The ImageDraw provides some 140 standard colour names, based on the colors supported by the X Window system and most web browsers. Colour names are case insensitive, and may contain whitespace. For example, "red" and "Red" both specify pure red.

The ImageDraw Module

Upvotes: 1

Related Questions