[cairo] Pycairo + PNG Output

Steve Chaplin stevech1097 at yahoo.com.au
Tue Oct 11 20:43:34 PDT 2005


On Tue, 2005-10-11 at 09:56 -0400, Owen Taylor wrote:
> On Tue, 2005-10-11 at 09:34 +0200, Ccx wrote:
> > Hello, I'm going to use Pycairo for generating graphics on webserver.
> > 
> > As far as I found out, Pycairo can be set to draw either to memory in a
> > raw data or to a png file, but not to a memory in png format which I need.
> > 
> > So I ask, is there way to do it with pycairo as it is or will it need
> > some reimplementation.
> > I can try to help in the second case, I have some experience with C, C++
> > and Python, but not with extending Python (I've just read the guide).
> 
> In C, you can do this with cairo_surface_write_to_png_stream() ...
> don't know if/how this is bound in the Python bindings. I'd think the
> natural mapping would be something like:
> 
>  buffer = StringIO.StringIO()
>  surface.write_to_png_stream(buffer)
>  pngData = buffer.getvalue()
>  buffer.close()

I dropped the 'stream' from pycairo since it seems to be a C++/Java
term, whereas the Python documentation talks about 'file objects' and
'file-like objects'.

pycairo release 1.0.2 has
   surface.write_to_png(f)
where 'f' can be a filename or a file object.

I've just updated cvs so that 'f' can now be a filename, a file object
or a file-like object that has a "write" method (like StringIO or
cStringIO). It can be used like this:

import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)

# write to filename
surface.write_to_png("/tmp/t1.png")

# write to file object
f2=file("/tmp/t2.png", "w")
surface.write_to_png(f2)
f2.close()

# write to object that has a "write" method
import StringIO
buffer = StringIO.StringIO()
surface.write_to_png(buffer)
png_string = buffer.getvalue()
buffer.close()
f3=file("/tmp/t3.png", "w")
f3.write(png_string)
f3.close()

# write to object that has a "write" method
import cStringIO
buffer = cStringIO.StringIO()
surface.write_to_png(buffer)
png_string = buffer.getvalue()
buffer.close()
f4=file("/tmp/t4.png", "w")
f4.write(png_string)
f4.close()

Steve

Send instant messages to your online friends http://au.messenger.yahoo.com 


More information about the cairo mailing list