0

I am trying to generate a PNG image which contains some custom text.
While creating the new image canvas there are multiple options to choose the mode of the image (Ex: P, PA, RGB, RGBA etc).
When I use the P mode, the rendered text is not anti-aliased.
Size of the result image is considerably smaller when used P mode compared to other modes like RGB, RGBA so, this would be my preference.
I would like to know why the font rendering is dependent on the color pallet? Is P mode (8-bit pixels ) with 256 colors are not sufficient to render the font?
When I use several of these png images as frames and generate a GIF image out of it, the quality of the image is reduced drastically. With <code>'P'</code> mode With <code>'RGB'</code> mode

As discussed on this thread, I do not want to resize the image which is a time consuming operation.

Below is the code which I have used:

fnt = ImageFont.truetype('Assets/somefont.ttf',82)
  b = Image.new('P',(680,120),color=255)
  #b = Image.new('RGB',(680,120),color=255)
  draw = ImageDraw.Draw(b)
  #draw.fontmode = "0"
  draw.text((b.width/2, (b.height-50)/2), "88", fill=0, font=fnt)
  f = BytesIO()
  b.save(f, format='PNG')

vikas kv
  • 386
  • 2
  • 15
  • Did you mean to put "Pip" in your question title? – FiddleStix Feb 14 '20 at 11:14
  • Pretty clear from the `python-imaging-library` tag that the questioner meant "PIL"; I edited to fix that. – djangodude Feb 14 '20 at 16:41
  • @djangodude, your edit is correct. That's my bad. But do you know the fix? – vikas kv Feb 20 '20 at 16:19
  • I put an answer, but re-reading your question I'm confused because you mention "creating the `GIF` image" but your code writes `PNG`. Maybe you can clarify your question a bit more and I will try to improve my answer. – djangodude Feb 20 '20 at 22:33

1 Answers1

0

2 things:

  • use mode 'PA' for your Image
  • convert to 'RGB' prior to saving

So your code becomes something like:

fnt = ImageFont.truetype('Assets/somefont.ttf',82)
b = Image.new('PA',(680,120),color=255)
draw = ImageDraw.Draw(b)
draw.text((b.width/2, (b.height-50)/2), "88", fill=0, font=fnt)
b = b.convert('RGB')
f = BytesIO()
b.save(f, format='PNG')

I got reasonable-looking results with this approach (different font, obviously, but you can see that it's anti-aliased): image using PA mode and RGB format

djangodude
  • 5,362
  • 3
  • 27
  • 39