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' 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")
I tried the following:
('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)
This however fails to draw the unicode character. It looks like I end up with an empty transparent image :(
What am I missing here? Is there a better way to draw text on a transparent image in python?
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.
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.
I have created a simple example below that draws unicode characters and saves them to a .png file.
The code above creates the png displayed below:
As a side note, I am using Pil 1.1.7 and Python 2.7.3 on Windows.
I think you have to make sure that your loaded font supports the characters your trying to output.
An example here: http://blog.wensheng.com/2006/03/how-to-create-images-from-chinese-text.html
In your examples you create a
RGBA
image, but you don't specify the value of thealpha
channel (so it defaults to 255). If you replace(255, 255, 255)
with(255,255,255,0)
it should work ok (as pixels with 0 alpha are transparent).To illustrate: