首页 > 解决方案 > 使用 PIL 绘制文本不适用于所有图像

问题描述

我正在尝试使用 PIL 在图像上绘制文本。但是,我只能在某些图像上看到文字。很多png都不起作用,比如这个:

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 作为颜色,但无济于事。

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

这个文本绘图功能是否仅适用于某些图像格式?

更新

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

标签: pythonimage-processingpython-imaging-library

解决方案


我想你只是得到了xy坐标错误的方式,并试图在一个 512 像素高的图像上写下 600 像素:

#!/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')

在此处输入图像描述


推荐阅读