繁体   English   中英

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

[英]How to draw unicode characters on transparent image in PIL

我正在尝试使用python绘制某些unicode字符和图像(准确地说是PIL)。

使用以下代码我可以生成带有白色背景的图像:

('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字符。 但是,不支持的字符应绘制为空方块(或默认值),因此您至少会看到某种输出。

我在下面创建了一个简单的示例,它绘制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文本

作为旁注,我在Windows上使用Pil 1.1.7和Python 2.7.3。

我认为您必须确保加载的字体支持您尝试输出的字符。

这里有一个例子: http//blog.wensheng.com/2006/03/how-to-create-images-from-chinese-text.html

font = ImageFont.truetype('simsun.ttc',24)

在您的示例中,您可以创建RGBA图像,但不指定alpha通道的值(因此默认为255)。 如果用(255,255,255,0) (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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM