我正在尝试使用 python(准确地说是 PIL)在图像上绘制某些 unicode 字符。
使用以下代码我可以生成具有白色背景的图像:
('entity_code'被传入方法)
size = self.font.getsize(entity_code)
im = Image.new("RGBA", size, (255,255,255))
draw = ImageDraw.Draw(im)
draw.text((0,6), entity_code, font=self.font, fill=(0,0,0))
del draw
img_buffer = StringIO()
im.save(img_buffer, format="PNG")
我尝试了以下方法:
('entity_code'被传入方法)
img = Image.new('RGBA',(100, 100))
draw = ImageDraw.Draw(img)
draw.text((0,6), entity_code, fill=(0,0,0), font=self.font)
img_buffer = StringIO()
img.save(img_buffer, 'GIF', transparency=0)
然而,这无法绘制 unicode 字符。看起来我最终得到了一个空的透明图像:(
我在这里错过了什么?有没有更好的方法在 python 中的透明图像上绘制文本?
最佳答案
您的代码示例到处都是,我倾向于同意@fraxel 的观点,即您在 RGBA 图像的填充颜色和背景颜色的使用方面不够具体。但是,我实际上根本无法使您的代码示例正常工作,因为我真的不知道您的代码如何组合在一起。
此外,正如@monkut 提到的,您需要查看您使用的字体,因为您的字体可能不支持特定的 unicode 字符。但是,不受支持的字符应绘制为空方 block (或任何默认值),这样您至少会看到某种输出。
我在下面创建了一个简单示例,它绘制 unicode 字符并将它们保存到 .png 文件中。
import Image,ImageDraw,ImageFont
# sample text and font
unicode_text = u"Unicode Characters: \u00C6 \u00E6 \u00B2 \u00C4 \u00D1 \u220F"
verdana_font = ImageFont.truetype("verdana.ttf", 20, encoding="unic")
# get the line size
text_width, text_height = verdana_font.getsize(unicode_text)
# create a blank canvas with extra space between lines
canvas = Image.new('RGB', (text_width + 10, text_height + 10), (255, 255, 255))
# draw the text onto the text canvas, and use black as the text color
draw = ImageDraw.Draw(canvas)
draw.text((5,5), unicode_text, font = verdana_font, fill = "#000000")
# save the blank canvas to a file
canvas.save("unicode-text.png", "PNG")
上面的代码创建了下面显示的 png:
附带说明一下,我在 Windows 上使用 Pil 1.1.7 和 Python 2.7.3。
关于python - 如何在PIL中的透明图像上绘制unicode字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11132894/