[cairo] output png fully-formatted png image to STDOUT or memory location

Dominic Lachowicz domlachowicz at gmail.com
Wed Feb 11 12:11:32 PST 2009


Hi Pablo,

> Im somewhat confused on how to use the write_to_png_stream() function.
> could you give a quick example?
>

You pass it a function to call whenever cairo wants to write PNG data,
as well as a user_data parameter. Your example would look something
like the following (error checking omitted):

cairo_status_t my_write_function(void *closure,
                                                unsigned char *data,
                                                unsigned int length)
{
  fwrite(data, 1, length, (FILE*)closure);
  return CAIRO_STATUS_SUCCESS;
}

cairo_surface_t* my_surface = ...;
cairo_surface_write_to_png_stream(my_surface, my_callback, stdout);

> also, could you provide a simple example of the logic needed to create the byte buffer???

The idea is to maintain a pointer to a grow-able region of memory, and
append 'length' bytes of 'data' to it in your callback. It's just like
a C++ vector, or a Glib GByteArray. How you implement that (eg. one
could use malloc/realloc plus memcpy, c++'s std::vector, a GString,
...) is left as an exercise for the reader.

Also, cairo's write_png() function is just a *very* small wrapper
around libpng. You could look at the sources of
http://cgit.freedesktop.org/cairo/tree/src/cairo-png.c, and easily
write your own write_png() function that saves an image surface's
data. That way, you could set the compression level without needing
any changes in cairo.

Best,
Dom


More information about the cairo mailing list