hbag
hbag

Reputation: 32

Pillow - KeyError when trying to write text on an image

I'm trying to write some text onto an image in Pillow, but for some reason it seems to constantly error out about a KeyError. I've tested this with multiple pre-written examples, so I'm fairly sure it's not my code. Here's a copy of the script and the error I'm getting:

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype("F25_Bank_Printer.ttf", 16)

img = Image.open('background.png')

title_text = "AUUUUUGH"
image_editable = ImageDraw.Draw(img)
image_editable.text((15,15), title_text, (237,230,211), font=font)


img.save('test_card.png')
Traceback (most recent call last):
  File "/usr/lib64/python3.9/site-packages/PIL/ImagePalette.py", line 99, in getcolor
    return self.colors[color]
KeyError: (237, 230, 211)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/hbag/git/novelty-scripts/scripts/probebadge.py", line 9, in <module>
    image_editable.text((15,15), title_text, (237,230,211), font=font)
  File "/usr/lib64/python3.9/site-packages/PIL/ImageDraw.py", line 339, in text
    ink = getink(fill)
  File "/usr/lib64/python3.9/site-packages/PIL/ImageDraw.py", line 302, in getink
    ink, fill = self._getink(fill)
  File "/usr/lib64/python3.9/site-packages/PIL/ImageDraw.py", line 112, in _getink
    ink = self.palette.getcolor(ink)
  File "/usr/lib64/python3.9/site-packages/PIL/ImagePalette.py", line 109, in getcolor
    self.palette[index + 256] = color[1]
IndexError: bytearray index out of range

And, just to be safe, here's the image I'm trying to draw on: A plain, redish-pink rectangle.

Upvotes: 0

Views: 964

Answers (1)

sk1p
sk1p

Reputation: 6735

Probably your problem is that the image you are trying to edit is indexed, that means that it doesn't have RGB colors available, but only a limited palette of colors. So (237,230,211) is not a RGB tuple, but indexes into the palette of the image.

By converting the image to RGB before trying to draw on it, you should be able to make it work:

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype("F25_Bank_Printer.ttf", 16)

img = Image.open('background.png')
img = img.convert('RGB')

title_text = "AUUUUUGH"
image_editable = ImageDraw.Draw(img)
image_editable.text((15,15), title_text, (237,230,211), font=font)


img.save('test_card.png')

Upvotes: 2

Related Questions