2012-06-21 87 views
3

我想绘制某些unicode字符和图像使用python(精确到PIL)。如何在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) 

但是, s画出unicode字符。它看起来像我结束了一个空的透明图像:(

我是什么在这里失踪?有没有更好的办法在python画一个透明图像上的文字?

回答

0

在你的例子,你创建一个RGBA形象,但你没有特异性y alpha通道的值(因此它默认为255)。如果您将(255, 255, 255)替换为(255,255,255,0),它应该可以正常工作(因为具有0 alpha的像素是透明的)。

举例说明:

import Image 
im = Image.new("RGBA", (200,200), (255,255,255)) 
print im.getpixel((0,0)) 
im2 = Image.new("RGBA", (200,200), (255,255,255,0)) 
print im2.getpixel((0,0)) 
#Output: 
(255, 255, 255, 255) 
(255, 255, 255, 0) 
2

你的代码示例是所有的地方,和我比较,你是不是在填充颜色的使用和背景颜色是不够具体@fraxel同意你的RGBA图像。然而,我实际上无法让你的代码示例工作,因为我真的不知道你的代码如何配合在一起。

此外,就像@monkut提到你需要看看你使用的字体,因为你的字体可能不支持特定的Unicode字符。但是,不支持的字符应该绘制为空方块(或任何默认值),因此您至少会看到某种输出。

我在下面创建了一个简单的例子,它绘制了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: unicode text

作为一个方面说明,我在Windows上使用弼1.1.7和Python 2.7.3。