Drawing text with PIL does not work on all images

烈酒焚心 提交于 2020-05-16 08:08:49

问题


I'm trying to draw text on images with PIL. However, I can see text on certain images only. A lot of png's don't work, such as this one:

http://r0k.us/graphics/kodak/kodim16.html

Code sample:

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from os.path import expanduser


im1=Image.open(expanduser('~/Desktop/in.png'))

# Drawing the text on the picture
font = ImageFont.truetype('/Library/Fonts/Songti.ttc', 100)
draw = ImageDraw.Draw(im1)
draw.text((50, 600), 'OMG!', fill="#aa0000", font=font)
draw = ImageDraw.Draw(im1)

# Save the image with a new name
im1.save(expanduser('~/Desktop/out.png'))

I've tried adding .convert("RGBA") and using RGB for colour, to no avail.

The code works on the photos taken from my iPhone. But when I use ImageMagick to convert those iPhone photos to .jpg or .png, the code stopped working again.

Is it that this text-drawing feature only works on certain image formats?

UPDATE

I added the actual text position to the .text() call. The code works on .png taken from iPhone.


回答1:


I think you just got the x and y coordinates the wrong way around and were trying to write 600 pixels down an image that is 512 pixels tall:

#!/usr/bin/env python3

import PIL
from PIL import Image, ImageFont, ImageDraw

im1=Image.open('start.png')

# Drawing the text on the picture
font = ImageFont.truetype('/Library/Fonts/Herculanum.ttf', 100)
draw = ImageDraw.Draw(im1)
draw.text((50, 200), 'OMG!', (255,0,255), font=font)

# Save the image with a new name
im1.save('result.png')



来源:https://stackoverflow.com/questions/53586795/drawing-text-with-pil-does-not-work-on-all-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!