Hate UML?

Draw sequence diagrams in seconds.

Copy a cairo surface to the windows clipboard
Posted on: 2008-09-19 10:00:00

I just spent several hours debugging clipboard copy of a DIB image. I could copy from my application, and paste into Paint. I could paste into Word. But if I pasted into WordPad, nothing showed up. If I pasted into GIMP, it crashed.

The general procedure is to fill out a BITMAPINFO structure, calculate the size of the image + row padding + the bitmap info structure itself, then allocate a memory handle with GlobalAlloc(). Finally, copy the BITMAPINFO structure into the given memory followed by the image pixel data.

What they don't tell you in MSDN is that, for maximum compatibility with other applications, you must use a positive value for the BITMAPINFOHEADER biHeight member. That means that you have to create the bitmap upside down

The other thing they don't tell you, unless you're reading really, really carefully, is that you have to insert padding at the end of the rows so that they always end at a DWORD (4 byte) boundary.

Anyway, here's a code snippet. Hopefully it will help somebody someday. If so, give me $2. Really.

// copy a cairo win32 surface (with dib) to the clipboard.
GraphicsClipboardSurface::copyToClipboard(HWND hwnd)
    cairo_surface_t* imageSurface = cairo_win32_surface_get_image( _surface );
    if ( imageSurface == NULL ) {
        return false;

    unsigned char* bits = cairo_image_surface_get_data( imageSurface );

    if ( bits == NULL ) {
        assert( false );
        return false;

    assert( cairo_image_surface_get_format( imageSurface ) == CAIRO_FORMAT_RGB24 );

    unsigned biSizeImage;
    memset( &bmi, 0, sizeof(bmi) );
    bmi.biSize = sizeof(bmi);
    bmi.biWidth = cairo_image_surface_get_width( imageSurface );
    bmi.biHeight= cairo_image_surface_get_height( imageSurface ); 

    unsigned rowPad = ( 4 - ( ( bmi.biWidth * 3 ) & 3 ) ) & 3;

    bmi.biPlanes = 1;
    bmi.biBitCount = 24; // 24 or 32. If 32, high byte is not used.
    bmi.biCompression = BI_RGB;
    biSizeImage = bmi.biWidth * bmi.biHeight * ( bmi.biBitCount / 8 ) + bmi.biHeight * rowPad;
    bmi.biXPelsPerMeter = (LONG)((double)96 * 100 / 2.54 + 0.5) ; // dpix
    bmi.biYPelsPerMeter = (LONG)((double)96 * 100 / 2.54 + 0.5); // dpiy
    bmi.biClrUsed = 0;
    bmi.biClrImportant = 0;

    HGLOBAL hMem = NULL;
    unsigned char* ptr = 0;
    unsigned size;
    bool success = false;

    // OpenClipboard
    if ( !OpenClipboard(hwnd) ) {
        return false;

    // call EmptyClipboard
    if ( !EmptyClipboard() ) {
        goto error;

    // calculate size of the data.
    size = bmi.biSize + biSizeImage;

    // Allocate the data using GlobalAlloc with GMEM_MOVEABLE flag.
    hMem = GlobalAlloc( GMEM_MOVEABLE, size );

    if ( hMem == NULL ) {
        goto error;

    ptr = (unsigned char*)GlobalLock( hMem );
    if ( ptr == 0 ) {
        goto error;

    // copy data to clipboard
    memcpy( ptr, &bmi, bmi.biSize );

    // copy each row of the bitmap in reverse order, adding padding after each
    // row.
    unsigned char* src = bits + bmi.biWidth * (bmi.biHeight-1) * 4;
    unsigned char* dest = ptr + bmi.biSize;
    for ( int i = 0; i < bmi.biHeight; i++ ) {
        for ( int j = 0; j < bmi.biWidth; j++ ) {
            *dest++ = *src++;
            *dest++ = *src++;
            *dest++ = *src++;

        dest += rowPad;
        src -= bmi.biWidth * 4 * 2;

    GlobalUnlock( hMem );

    // Call SetClipboardData
    if ( !SetClipboardData( CF_DIB, hMem ) ) {
        goto error;

    hMem = NULL; 

    success = true;
    if ( hMem ) {
        GlobalFree( hMem );
    return success;

On the plus side, websequencediagrams.com Desktop Edition is coming along very nicely. I implemented Print yesterday. It should be ready soon... Hopefully some companies will buy it. Here's a screenshot.

Update: Of course, by 2011 desktop applications are gone. I made the right call by not finishing the desktop version, and just licensing the whole webserver. More information on this strategy is in C++: A language for next generation web apps

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):


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