如何在PIL中的透明图像上绘制Unicode字符

3
我将尝试使用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中绘制透明图像上的文本?
3个回答

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操作系统上使用Pil 1.1.7和Python 2.7.3。


0

0
在您的示例中,您创建了一个RGBA图像,但未指定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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接