Creating Transparent Images from Text in Python
Thu, 01 Feb 2007 15:02:56 -0600
In the project I am currently working on, I have to take data from a form field and generate images from it. These images need to have a transparent background. Here is the way I did that:
# create the original canvas giving it width and height
canvas = Image.new("RGBA", (W,H))
# select a font (you need to have compiled PIL with freetype installed for the
#_imagingft module to be on the server. This is necessary for this process.
font = ImageFont.truetype("/path/to/ttf/font", size_int)
# setup image to draw text on it
draw = ImageDraw.Draw(canvas)
black = "#000000"
# draw text on canvas, using offsets from upper left corner
draw.text((25,2),text,fill=black,font=font)
newImg = someFileHandle
canvas.save(newImg, "image_type")
newImg.close()
Done!
# create the original canvas giving it width and height
canvas = Image.new("RGBA", (W,H))
# select a font (you need to have compiled PIL with freetype installed for the
#_imagingft module to be on the server. This is necessary for this process.
font = ImageFont.truetype("/path/to/ttf/font", size_int)
# setup image to draw text on it
draw = ImageDraw.Draw(canvas)
black = "#000000"
# draw text on canvas, using offsets from upper left corner
draw.text((25,2),text,fill=black,font=font)
newImg = someFileHandle
canvas.save(newImg, "image_type")
newImg.close()
Done!




