Python Imaging Library - Text rendering

前端 未结 6 953
终归单人心
终归单人心 2020-11-28 03:49

I\'m trying to render some text using PIL, but the result that comes out is, frankly, crap.

For example, here\'s some text I wrote in Photoshop:

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 03:51

    Try using pycairo - the python bindings for the Cairo drawing library -- it is usefull for more refined drawing, with antialiased lines, and such - and you can generate vector based images as well

    Correctly handling fonts, and layout is complicated, and requires the use of the "pango" and "pangocairo" libraries as well. Although they are made for serious font work (all GTK+ widgets do use pango for font rendering), the available docuemtnation and examples are extremely poor.

    The sample bellow shows the prints available in the system and renders the sample text in a font family passed as parameter on the command line.

    # -*- coding: utf-8 -*-
    import cairo
    import pango
    import pangocairo
    import sys
    
    surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 320, 120)
    context = cairo.Context(surf)
    
    #draw a background rectangle:
    context.rectangle(0,0,320,120)
    context.set_source_rgb(1, 1, 1)
    context.fill()
    
    #get font families:
    
    font_map = pangocairo.cairo_font_map_get_default()
    families = font_map.list_families()
    
    # to see family names:
    print [f.get_name() for f in   font_map.list_families()]
    
    #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    
    # Positions drawing origin so that the text desired top-let corner is at 0,0
    context.translate(50,25)
    
    pangocairo_context = pangocairo.CairoContext(context)
    pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    
    layout = pangocairo_context.create_layout()
    fontname = sys.argv[1] if len(sys.argv) >= 2 else "Sans"
    font = pango.FontDescription(fontname + " 25")
    layout.set_font_description(font)
    
    layout.set_text(u"Travis L.")
    context.set_source_rgb(0, 0, 0)
    pangocairo_context.update_layout(layout)
    pangocairo_context.show_layout(layout)
    
    with open("cairo_text.png", "wb") as image_file:
        surf.write_to_png(image_file)
    

    Rendred image

提交回复
热议问题