LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Python: Can you add text to an image in python? (http://www.linuxquestions.org/questions/programming-9/python-can-you-add-text-to-an-image-in-python-632773/)

BrianK 04-03-2008 02:52 PM

Python: Can you add text to an image in python?
 
Can I use python to put text on an image, like "Property of me" or the file name something of the sort? What about multiple bits of text, like "proeprty of" AND the file name in separate corners of the image?

I know I can do it with imagemagick, I'm just wondering if I can do it directly inside of python (without calling an external program).

ranger_nemo 04-03-2008 04:48 PM

The Python Imaging Library should be able to do such...

http://www.pythonware.com/products/pil/

BrianK 04-03-2008 04:56 PM

Quote:

Originally Posted by ranger_nemo (Post 3109825)
The Python Imaging Library should be able to do such...

http://www.pythonware.com/products/pil/

indeed.

If anyone else is interested, here's my quick example (complete with transparency):
Code:

import Image, ImageDraw, ImageFont
from os import chdir, path

def txt2img(text,bg="#ffffff",fg="#000000",font="Verdana.ttf",FontSize=14):
    font_dir = "/usr/share/fonts/truetype/msttcorefonts/"
    img_name = "sweet.jpg"
    font_size = FontSize
    fnt = ImageFont.truetype(font_dir+font, font_size)
    lineWidth = 20
    img = Image.open("ayo20.jpg")
    imgbg = Image.new('RGBA', img.size, "#000000") # make an entirely black image
    mask = Image.new('L',img.size,"#000000")      # make a mask that masks out all
    draw = ImageDraw.Draw(img)                    # setup to draw on the main image
    drawmask = ImageDraw.Draw(mask)                # setup to draw on the mask
    drawmask.line((0, lineWidth/2, img.size[0],lineWidth/2),
                  fill="#999999", width=10)        # draw a line on the mask to allow some bg through
    img.paste(imgbg, mask=mask)                    # put the (somewhat) transparent bg on the main
    draw.text((10,0), text, font=fnt, fill=bg)      # add some text to the main
    del draw
    img.save(img_name,"JPEG",quality=100) 



txt2img("This is a really weird image")

before:
http://hero.com/~briank/misc/ex/ayo20.jpg

after:
http://hero.com/~briank/misc/ex/sweet.jpg


All times are GMT -5. The time now is 10:01 AM.