cutebear
cutebear

Reputation: 25

pillow can not draw text with fill

i draw a text to a image and i set the fill and i get an error , but i do not for the fill it get nothing for my image

from PIL import Image, ImageDraw
img = Image.open('test.png')

d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill="red")

img.save('testssss.png')

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 99, in getcolor
    return self.colors[color]
KeyError: (255, 0, 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    d.text((100, 100), "HELLO", fill="red")
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 455, in text
    ink = getink(fill)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 403, in getink
    ink, fill = self._getink(fill)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 111, in _getink
    ink = self.palette.getcolor(ink)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImagePalette.py", line 109, in getcolor
    self.palette[index + 256] = color[1]
IndexError: bytearray index out of range

The image:

enter image description here

my system : replit(linux)

Upvotes: 1

Views: 1960

Answers (1)

anarchy
anarchy

Reputation: 5184

Try, (255,0,0) instead of red.

from PIL import Image, ImageDraw
img = Image.open('test.png')

d = ImageDraw.Draw(img)
d.text((100, 100), "HELLO", fill=(255,0,0))

img.save('testssss.png')

You should also look at the size of your image, it might be too small for the text you are using. You can try reducing from (100,100) to maybe (10,10) first and see if it works.

It could also be a case where you don’t have enough bits for the colour because your image is less than 256 bits per colour palette. You can also try converting your image to an rgb image using the following command before you add the text. Do

img = img.convert("RGB")

Upvotes: 1

Related Questions