Hate UML?

Draw sequence diagrams in seconds.

cairo blur image surface
Posted on: 2009-03-14 13:34:45
This really should have been included in cairo. Instead, everyone that wants to have shadows has to roll their own blur function. Here's my take on it. I'll even release this into the public domain.

This is used in the back-end for www.websequencediagrams.com.

// to build:
// gcc -I/usr/include/cairo -lcairo -o blur blur.c

#include <stdlib.h>
#include <memory.h>
#include <stdio.h>
#include "cairo.h"

void cairo_image_surface_blur( cairo_surface_t* surface, double radius )
    // Steve Hanov, 2009
    // Released into the public domain.
    // get width, height
    int width = cairo_image_surface_get_width( surface );
    int height = cairo_image_surface_get_height( surface );
    unsigned char* dst = (unsigned char*)malloc(width*height*4);
    unsigned* precalc = 
    unsigned char* src = cairo_image_surface_get_data( surface );
    double mul=1.f/((radius*2)*(radius*2));
    int channel;
    // The number of times to perform the averaging. According to wikipedia,
    // three iterations is good enough to pass for a gaussian.
    const MAX_ITERATIONS = 3; 
    int iteration;

    memcpy( dst, src, width*height*4 );

    for ( iteration = 0; iteration < MAX_ITERATIONS; iteration++ ) {
        for( channel = 0; channel < 4; channel++ ) {
            int x,y;

            // precomputation step.
            unsigned char* pix = src;
            unsigned* pre = precalc;

            pix += channel;
            for (y=0;y<height;y++) {
                for (x=0;x<width;x++) {
                    int tot=pix[0];
                    if (x>0) tot+=pre[-1];
                    if (y>0) tot+=pre[-width];
                    if (x>0 && y>0) tot-=pre[-width-1];
                    pix += 4;

            // blur step.
            pix = dst + (int)radius * width * 4 + (int)radius * 4 + channel;
            for (y=radius;y<height-radius;y++) {
                for (x=radius;x<width-radius;x++) {
                    int l = x < radius ? 0 : x - radius;
                    int t = y < radius ? 0 : y - radius;
                    int r = x + radius >= width ? width - 1 : x + radius;
                    int b = y + radius >= height ? height - 1 : y + radius;
                    int tot = precalc[r+b*width] + precalc[l+t*width] - 
                        precalc[l+b*width] - precalc[r+t*width];
                    *pix=(unsigned char)(tot*mul);
                    pix += 4;
                pix += (int)radius * 2 * 4;
        memcpy( src, dst, width*height*4 );

    free( dst );
    free( precalc );

int main(int argc, char* argv[])
    cairo_surface_t* surface;
    cairo_t* ctx;
    cairo_text_extents_t text_extents;
    cairo_font_extents_t font_extents;
    double FontSize = 100;
    double radius = 7;
    double width, height;

    if ( argc != 3 ) {
        printf("Syntax: %s <outfile.png> \"<text to display>\"\n", argv[0]);
        return -1;

    // Get text size.
    surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, 10, 10 );
    ctx = cairo_create( surface );
    cairo_set_font_size( ctx, FontSize );

    cairo_font_extents( ctx, &font_extents );
    cairo_text_extents( ctx, argv[2], &text_extents );

    height = font_extents.ascent + font_extents.descent + radius * 2;
    width = text_extents.x_advance + radius * 2;

    cairo_destroy( ctx );
    cairo_surface_destroy( surface );

    // Draw text.
    surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, width, height );

    ctx = cairo_create( surface );
    cairo_set_font_size( ctx, FontSize );

    cairo_move_to( ctx, 0 + radius, font_extents.ascent + radius );
    cairo_show_text( ctx, argv[2] );
    cairo_fill( ctx );

    cairo_image_surface_blur( surface, 5 );

    cairo_move_to( ctx, 0, font_extents.ascent );
    cairo_show_text( ctx, argv[2] );
    cairo_fill( ctx );

    cairo_destroy( ctx );

    cairo_surface_write_to_png( surface, argv[1] );

    cairo_surface_destroy( surface );

    return 0;

Want more programming tech talk?
Add to Circles on Google Plus
Subscribe to posts

Post comment

Real Name:
Your Email (Not displayed):

Text only. No HTML. If you write "http:" your message will be ignored.
Choose an edit password if you want to be able to edit or delete your comment later.
Editing Password (Optional):


2009-03-14 19:27:37
Why not use a simple iir guassian or iir triangular filter instead of summed area tables?


2009-03-14 20:45:53
Why not just release it under the same copyright as cairo itself?


2009-03-14 22:11:13
Why not send them a patch?


2009-03-14 23:13:36
why not have a beer?

Neil Dickson

2009-03-14 23:42:19
If you'd like the blur step a bit faster, the bounds checking on l, t, r, and b aren't needed since you've already bounded the range properly on the for-loop lines. With a simple adjustment on top of that, you could eliminate the multiplication and addition to find the indices into precalc by just adding to l, t, r, and b. You can also make mul a 16.16 fixed-point number to speed up the multiplication with tot. The branches that are almost always true in the precomputation loops can be handled with separate loops for the edge cases, reducing the extra overhead, and turning the double-loop into a single-loop.

Lastly, if you don't mind reduced readability, you can vectorize the precomputation and blur steps. The precalc lookups don't look like they can really be vectorized, though, so it might not help much for the blur step.

I realize that you're probably not interested in speeding it up at all, unless you're using it in animated sequences, but you could probably get it 3-10 times faster than it is now if you'd like. :) If you are interested, just give me a shout.



2009-03-15 00:54:21

2009-03-14 20:45:53

Why not just release it under the same copyright as cairo itself?


2009-03-14 22:11:13

Why not send them a patch?"

It's public domain, you can do it.

Fan of Chris

2009-03-19 21:17:03

2009-03-15 00:54:21


2009-03-14 20:45:53

Why not just release it under the same copyright as cairo itself?


2009-03-14 22:11:13

Why not send them a patch?"

It's public domain, you can do it.


2009-04-28 04:28:14
oh, why cairo is NOT so much simple to understand..

please somebody, can explain the meaning of each line in this code...

I just only a little bit get the meaning of this code.. made compilation.. it work fantastic... BUT where in this code exactly place of put and get the pixels (alpha and color) from the surface?

Do anyone have any documentation to Cairo.. Please help.


2009-04-28 15:00:07
Comments and documentation are for the weak.

Other posts by Steve

Yes, You Absolutely Might Possibly Need an EIN to Sell Software to the US How Asana Breaks the Rules About Per-Seat Pricing 5 Ways PowToon Made Me Want to Buy Their Software How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets UMA and free long distance UMA's dirty secrets Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets