Home » Create an image using PyCairo

Create an image using PyCairo

Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course

Pycairo is a Python module providing bindings for the cairo graphics library

Cairo is a 2D graphics library with support for multiple output devices. Currently supported output targets include the X Window System (via both Xlib and XCB), Quartz, Win32, image buffers, PostScript, PDF, and SVG file output. Experimental backends include OpenGL, BeOS, OS/2, and DirectFB.

Table of Contents

Installation:

  • pip install pycairo

Code

In this example we create a basic image with some text on it

import cairo
        
def main():
    
    ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, 390, 60)
    cr = cairo.Context(ims)
    
    cr.set_source_rgb(0, 0, 0)
    cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL,
        cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(40)
    
    cr.move_to(10, 50)
    cr.show_text("A test image.")

    ims.write_to_png("image.png")
        
        
if __name__ == "__main__":    
    main()

This example is a small console application that creates a PNG image with some text in it

First we need to import the cairo module

import cairo

Then we create a surface and a Cairo context from the surface. The surface is a 468×80 px image.

ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, 468, 80)
cr = cairo.Context(ims)

We draw our text in black. The color is specified with the set_source_rgb() method.

cr.set_source_rgb(0, 0, 0)

We then choose a font type with the select_font_face() method and set its size to 30 with the set_font_size() method.

cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(30)

We move to the position at x=10.0, y=10.0 within the image and draw our text.

cr.move_to(10, 10)
cr.show_text("A test image.")

Now we save this as a png file called image.png

ims.write_to_png("image.png")

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More