Search code examples
canimationgraphicsgtkcairo

How to composite multiple PNG into a single PNG using GTK/Cairo


I'm somewhat new to GTK and very new to Cairo. I've been tasked to create an application that needs to take a PNG as a background and composite multiple PNG files that contains letters and numbers onto the background PNG so that I end up with a single PNG that can then be transformed, rotated, scaled etc. Any hints, tutorials, code samples that I might find useful? As is the case with GTK, the Cairo documentation appears somewhat lacking for a beginner trying to do something more complex than drawing shapes.


Solution

  • Take a look at this simple example. It uses only cairo:

    #include <cairo.h>
    
    int main()
    {
        //Load a few images from files
        cairo_surface_t *surf1 = cairo_image_surface_create_from_png("a.png");
        cairo_surface_t *surf2 = cairo_image_surface_create_from_png("b.png");
    
        //Create the background image
        cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 100, 100);
    
        //Create the cairo context
        cairo_t *cr = cairo_create(img);
    
        //Initialize the image to black transparent
        cairo_set_source_rgba(cr, 0,0,0, 1);
        cairo_paint(cr);
    
        //Paint one image
        cairo_set_source_surface(cr, surf1, 0, 0);
        cairo_paint(cr);
    
        //Paint the other image
        cairo_set_source_surface(cr, surf2, 50, 50);
        cairo_paint(cr);
    
        //Destroy the cairo context and/or flush the destination image
        cairo_surface_flush(img);
        cairo_destroy(cr);
    
        //And write the results into a new file
        cairo_surface_write_to_png(img, "result.png");
    
        //Be tidy and collect your trash
        cairo_surface_destroy(img);
        cairo_surface_destroy(surf1);
        cairo_surface_destroy(surf2);
    
        return 0;
    
    }