Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

Is there a more efficient way to create images using python PIL?

I'm trying to generate an image that contains the text of a given string. For now I'm using the Image.draw.text() from the Pyhton PIL library to generate the result and the process is working fine, but it's exceedingly slow and it takes a handful of seconds to finish drawing, which is really hampering the scalability of the program.

This is the current function to generate images:

def draw_ascii(ascii_image, new_width) :
    # Source text, and wrap it.
    adjusted_ascii = ascii_image.replace("
", " ")
    text = textwrap.fill(adjusted_ascii, new_width)

    # Font size, color and type.
    fontcolor = (0, 0, 0)
    fontsize = 14
    font = ImageFont.truetype("FreeMono.ttf", fontsize)

    # Determine text size using a scratch image.
    img = Image.new("RGBA", (1,1))
    draw = ImageDraw.Draw(img)
    textsize = draw.textsize(text, font)

    # Creating the final image and put the text on it
    background = (255, 255, 255)
    img = Image.new("RGB", textsize, background)
    draw = ImageDraw.Draw(img)
    draw.text((0, 0), text, fontcolor, font)

    return(img)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...