问题描述
我正在尝试使用python(准确地说是PIL)在图像上绘制某些unicode字符.
I am trying to draw certain unicode characters on and image using python (PIL to be precise).
使用以下代码,我可以生成白色背景的图像:
Using the following code I can generate the images with a white background:
('entity_code'被传递到方法中)
('entity_code' is passed in to the method)
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'被传递到方法中)
('entity_code' is passed in to the method)
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字符.看来我最终得到了一个空的透明图像:(
This however fails to draw the unicode character. It looks like I end up with an empty transparent image :(
我在这里想念什么?是否有更好的方法在python中的透明图像上绘制文本?
What am I missing here? Is there a better way to draw text on a transparent image in python?
推荐答案
您的代码示例无处不在,我倾向于同意@fraxel的意见,即您对填充色和颜色的使用不够具体. RGBA图像的背景颜色.但是,实际上我根本无法使您的代码示例正常工作,因为我真的不知道您的代码如何组合在一起.
Your code examples are all over the place, and I am inclined to agree with @fraxel that you are not being specific enough in the usage of fill colors and the background colors for your RGBA images. However I can't actually get your code example to work at all because I don't really have any idea of how your code fits together.
此外,就像@monkut提到的那样,您需要查看所使用的字体,因为您的字体可能不支持特定的unicode字符.但是,不支持的字符应绘制为一个空的正方形(或任何默认值),这样您至少会看到某种输出.
Also, just like @monkut mentioned you need to look at the font you are using because your font may not support specific unicode characters. However unsupported characters should be drawn as a empty square (or whatever the default value is) so you would at least see some kind of output.
我在下面创建了一个简单的示例,该示例绘制Unicode字符并将其保存到.png文件中.
I have created a simple example below that draws unicode characters and saves them to a .png file.
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:
The code above creates the png displayed below:
请注意,我在Windows上使用的是Pil 1.1.7和Python 2.7.3.
As a side note, I am using Pil 1.1.7 and Python 2.7.3 on Windows.
这篇关于如何在PIL中的透明图像上绘制unicode字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!