How do I write an image into an SVG file using cairo?
Asked Answered
M

3

10

I have some code that looks like this:

cairo_surface_t * surface = cairo_svg_surface_create("0.svg", 512, 512);
cairo_t * context = cairo_create(surface);

int * data = new int[512*512];

// fill the data...

cairo_surface_t * image_surface = 
    cairo_image_surface_for_data(data, 512, 512, 512*4);
cairo_set_source_surface(context, image_surface, 0, 0);
cairo_paint(context);

// do some other drawing ...

cairo_surface_flush(surface);
cairo_surface_finish(surface);
cairo_surface_destroy(surface);
cairo_destroy(context);

However, the svg always appears corrupted. The image is not properly written, and all drawing commands following do not work. Changing the surface type to PS, ie:

cairo_surface_t * surface = cairo_ps_surface_create("0.ps", 512, 512);

produces a perfectly correct PS document. Any help fixing the SVG would be appreciated.

EDIT: Forgot to provide version info. Cairo 1.10.2 as given by cairo_version_string(). g++ 4.52 Running on Ubuntu 11.04

EDIT(2): Ok, I have traced this down to PNG problems with cairo and discovered that cairo_surface_write_to_png does not behave as expected either. Both this function and attempting to embed an image in an SVG cause "out of memory errors", and I still don't know why.

Mcallister answered 29/7, 2011 at 0:8 Comment(0)
O
2

Looks like you may have forgotten to specify the SVG version as:

cairo_svg_surface_restrict_to_version (surface, CAIRO_SVG_VERSION_1_2);

You can do this immediately after creating the surface.

Onstad answered 4/8, 2011 at 11:41 Comment(1)
OK. Looking at your version above, this should be CAIRO_SVG_VERSION_1_1. On the PNG issue, can you cairo_image_surface_create_from_png() and then write the surface back to a new PNG and have the file be corrupt? Or does this work properly?Onstad
I
0

Perhaps publishing the resulting plain SVG can help.

Ironstone answered 11/9, 2011 at 12:48 Comment(0)
D
0

I cannot find cairo_image_surface_for_data in the Cairo documentation. Did you mean cairo_image_surface_create_for_data? If so, you need to use cairo_format_stride_for_width to calculate the array size, and the bitmap data needs to be in the format Cairo expects. Since both of your outputs are corrupted, this strongly suggests that the problem is with the input.

Doolie answered 23/9, 2011 at 2:10 Comment(2)
@Scott, you still there? Have you tried Seth's suggestion to load the source surface from a png?Doolie
i forgot about this question completely, sorry. I didn't solve it, but i found that cairo with PNGs worked fine in other projects on my computer. I think that because I was linking against both Irrlicht and OpenCV with this project, that there were some linking issues about which version of libpng to use.Mcallister

© 2022 - 2024 — McMap. All rights reserved.