使用PIL绘制文字并不适用于所有图像 [英] Drawing text with PIL does not work on all images

查看:114
本文介绍了使用PIL绘制文字并不适用于所有图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在具有PIL的图像上绘制文本.但是,我只能在某些图像上看到文本.许多png无效,例如以下一种:

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

代码示例:

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'))

我尝试添加.convert("RGBA")并将RGB用作颜色,但无济于事.

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

该代码适用于从我的iPhone拍摄的照片.但是,当我使用ImageMagick将这些iPhone照片转换为.jpg或.png时,代码再次停止工作.

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?

更新

我在.text()调用中添加了实际的文本位置.该代码适用于从iPhone提取的.png.

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

推荐答案

我认为您只是错误地找到了xy坐标,并试图在512像素高的图像上写入600像素:

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')

这篇关于使用PIL绘制文字并不适用于所有图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆