Code

44a977df7ff3180a876057100f31d33a4407e7c0
[inkscape.git] / src / helper / png-write.cpp
1 #define __SP_PNG_WRITE_C__
3 /*
4  * PNG file format utilities
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   Whoever wrote this example in libpng documentation
9  *
10  * Copyright (C) 1999-2002 authors
11  *
12  * Released under GNU GPL, read the file 'COPYING' for more information
13  */
15 #ifdef HAVE_CONFIG_H
16 # include "config.h"
17 #endif
19 #include <interface.h>
20 #include <libnr/nr-pixops.h>
21 #include <glib/gmessages.h>
22 #include <png.h>
23 #include "png-write.h"
24 #include "io/sys.h"
25 #include <display/nr-arena-item.h>
26 #include <display/nr-arena.h>
27 #include <document.h>
28 #include <sp-item.h>
29 #include <sp-root.h>
30 #include <sp-defs.h>
32 /* This is an example of how to use libpng to read and write PNG files.
33  * The file libpng.txt is much more verbose then this.  If you have not
34  * read it, do so first.  This was designed to be a starting point of an
35  * implementation.  This is not officially part of libpng, and therefore
36  * does not require a copyright notice.
37  *
38  * This file does not currently compile, because it is missing certain
39  * parts, like allocating memory to hold an image.  You will have to
40  * supply these parts to get it to compile.  For an example of a minimal
41  * working PNG reader/writer, see pngtest.c, included in this distribution.
42  */
44 /* write a png file */
46 typedef struct SPPNGBD {
47         const guchar *px;
48         int rowstride;
49 } SPPNGBD;
51 static int
52 sp_png_get_block_stripe (const guchar **rows, int row, int num_rows, void *data)
53 {
54         SPPNGBD *bd = (SPPNGBD *) data;
56         for (int r = 0; r < num_rows; r++) {
57                 rows[r] = bd->px + (row + r) * bd->rowstride;
58         }
60         return num_rows;
61 }
63 int
64 sp_png_write_rgba (const gchar *filename, const guchar *px, int width, int height, double xdpi, double ydpi, int rowstride)
65 {
66         SPPNGBD bd;
68         bd.px = px;
69         bd.rowstride = rowstride;
71         return sp_png_write_rgba_striped (filename, width, height, xdpi, ydpi, sp_png_get_block_stripe, &bd);
72 }
74 int
75 sp_png_write_rgba_striped (const gchar *filename, int width, int height, double xdpi, double ydpi,
76                            int (* get_rows) (const guchar **rows, int row, int num_rows, void *data),
77                            void *data)
78 {
79         FILE *fp;
80         png_structp png_ptr;
81         png_infop info_ptr;
82         png_color_8 sig_bit;
83         png_text text_ptr[3];
84         png_uint_32 r;
86         g_return_val_if_fail (filename != NULL, FALSE);
88         /* open the file */
90         Inkscape::IO::dump_fopen_call(filename, "M");
91         fp = Inkscape::IO::fopen_utf8name(filename, "wb");
92         g_return_val_if_fail (fp != NULL, FALSE);
94         /* Create and initialize the png_struct with the desired error handler
95          * functions.  If you want to use the default stderr and longjump method,
96          * you can supply NULL for the last three parameters.  We also check that
97          * the library version is compatible with the one used at compile time,
98          * in case we are using dynamically linked libraries.  REQUIRED.
99          */
100         png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
102         if (png_ptr == NULL) {
103                 fclose(fp);
104                 return FALSE;
105         }
107         /* Allocate/initialize the image information data.  REQUIRED */
108         info_ptr = png_create_info_struct(png_ptr);
109         if (info_ptr == NULL) {
110                 fclose(fp);
111                 png_destroy_write_struct(&png_ptr, NULL);
112                 return FALSE;
113         }
115         /* Set error handling.  REQUIRED if you aren't supplying your own
116          * error hadnling functions in the png_create_write_struct() call.
117          */
118         if (setjmp(png_ptr->jmpbuf)) {
119                 /* If we get here, we had a problem reading the file */
120                 fclose(fp);
121                 png_destroy_write_struct(&png_ptr, &info_ptr);
122                 return FALSE;
123         }
125         /* set up the output control if you are using standard C streams */
126         png_init_io(png_ptr, fp);
128         /* Set the image information here.  Width and height are up to 2^31,
129          * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
130          * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
131          * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
132          * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
133          * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
134          * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
135          */
136         png_set_IHDR(png_ptr, info_ptr,
137                      width,
138                      height,
139                      8, /* bit_depth */
140                      PNG_COLOR_TYPE_RGB_ALPHA,
141                      PNG_INTERLACE_NONE,
142                      PNG_COMPRESSION_TYPE_BASE,
143                      PNG_FILTER_TYPE_BASE);
145         /* otherwise, if we are dealing with a color image then */
146         sig_bit.red = 8;
147         sig_bit.green = 8;
148         sig_bit.blue = 8;
149         /* if the image has an alpha channel then */
150         sig_bit.alpha = 8;
151         png_set_sBIT(png_ptr, info_ptr, &sig_bit);
153         /* Made by Inkscape comment */
154         text_ptr[0].key = "Software";
155         text_ptr[0].text = "www.inkscape.org";
156         text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE;
157         png_set_text(png_ptr, info_ptr, text_ptr, 1);
159         /* other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs, */
160         /* note that if sRGB is present the cHRM chunk must be ignored
161          * on read and must be written in accordance with the sRGB profile */
162         png_set_pHYs(png_ptr, info_ptr, unsigned(xdpi / 0.0254 + 0.5), unsigned(ydpi / 0.0254 + 0.5), PNG_RESOLUTION_METER); 
164         /* Write the file header information.  REQUIRED */
165         png_write_info(png_ptr, info_ptr);
167         /* Once we write out the header, the compression type on the text
168          * chunks gets changed to PNG_TEXT_COMPRESSION_NONE_WR or
169          * PNG_TEXT_COMPRESSION_zTXt_WR, so it doesn't get written out again
170          * at the end.
171          */
173         /* set up the transformations you want.  Note that these are
174          * all optional.  Only call them if you want them.
175          */
177         /* --- CUT --- */
179         /* The easiest way to write the image (you may have a different memory
180          * layout, however, so choose what fits your needs best).  You need to
181          * use the first method if you aren't handling interlacing yourself.
182          */
184         r = 0;
185         while (r < static_cast< png_uint_32 > (height) ) {
186                 png_bytep row_pointers[64];
187                 int h, n;
189                 h = MIN (height - r, 64);
190                 n = get_rows ((const unsigned char **) row_pointers, r, h, data);
191                 if (!n) break;
192                 png_write_rows (png_ptr, row_pointers, n);
193                 r += n;
194         }
196         /* You can write optional chunks like tEXt, zTXt, and tIME at the end
197          * as well.
198          */
200         /* It is REQUIRED to call this to finish writing the rest of the file */
201         png_write_end(png_ptr, info_ptr);
203         /* if you allocated any text comments, free them here */
205         /* clean up after the write, and free any memory allocated */
206         png_destroy_write_struct(&png_ptr, &info_ptr);
208         /* close the file */
209         fclose(fp);
211         /* that's it */
212         return TRUE;
217 struct SPEBP {
218     int width, height, sheight;
219     guchar r, g, b, a;
220     NRArenaItem *root; // the root arena item to show; it is assumed that all unneeded items are hidden
221     guchar *px;
222     unsigned (*status)(float, void *);
223     void *data;
224 };
227 /**
228  *
229  */
230 static int
231 sp_export_get_rows(guchar const **rows, int row, int num_rows, void *data)
233     struct SPEBP *ebp = (struct SPEBP *) data;
235     if (ebp->status) {
236         if (!ebp->status((float) row / ebp->height, ebp->data)) return 0;
237     }
239     num_rows = MIN(num_rows, ebp->sheight);
240     num_rows = MIN(num_rows, ebp->height - row);
242     /* Set area of interest */
243     NRRectL bbox;
244     bbox.x0 = 0;
245     bbox.y0 = row;
246     bbox.x1 = ebp->width;
247     bbox.y1 = row + num_rows;
248     /* Update to renderable state */
249     NRGC gc(NULL);
250     nr_matrix_set_identity(&gc.transform);
252     nr_arena_item_invoke_update(ebp->root, &bbox, &gc,
253            NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
255     NRPixBlock pb;
256     nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
257                              bbox.x0, bbox.y0, bbox.x1, bbox.y1,
258                              ebp->px, 4 * ebp->width, FALSE, FALSE);
260     for (int r = 0; r < num_rows; r++) {
261         guchar *p = NR_PIXBLOCK_PX(&pb) + r * pb.rs;
262         for (int c = 0; c < ebp->width; c++) {
263             *p++ = ebp->r;
264             *p++ = ebp->g;
265             *p++ = ebp->b;
266             *p++ = ebp->a;
267         }
268     }
270     /* Render */
271     nr_arena_item_invoke_render(ebp->root, &bbox, &pb, 0);
273     for (int r = 0; r < num_rows; r++) {
274         rows[r] = NR_PIXBLOCK_PX(&pb) + r * pb.rs;
275     }
277     nr_pixblock_release(&pb);
279     return num_rows;
282 /**
283 Hide all items which are not listed in list, recursively, skipping groups and defs
284 */
285 static void
286 hide_other_items_recursively(SPObject *o, GSList *list, unsigned dkey)
288     if (SP_IS_ITEM(o)
289         && !SP_IS_DEFS(o)
290         && !SP_IS_ROOT(o)
291         && !SP_IS_GROUP(o)
292         && !g_slist_find(list, o))
293     {
294         sp_item_invoke_hide(SP_ITEM(o), dkey);
295     }
297      // recurse
298     if (!g_slist_find(list, o)) {
299         for (SPObject *child = sp_object_first_child(o) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
300             hide_other_items_recursively(child, list, dkey);
301         }
302     }
306 /**
307  *  Render the SVG drawing onto a PNG raster image, then save to
308  *  a file.  Returns TRUE if succeeded in writing the file,
309  *  FALSE otherwise.
310  */
311 int
312 sp_export_png_file(SPDocument *doc, gchar const *filename,
313                    double x0, double y0, double x1, double y1,
314                    unsigned width, unsigned height, double xdpi, double ydpi,
315                    unsigned long bgcolor,
316                    unsigned (*status)(float, void *),
317                    void *data, bool force_overwrite,
318                    GSList *items_only)
320     int write_status = TRUE;
321     g_return_val_if_fail(doc != NULL, FALSE);
322     g_return_val_if_fail(filename != NULL, FALSE);
323     g_return_val_if_fail(width >= 1, FALSE);
324     g_return_val_if_fail(height >= 1, FALSE);
326     if (!force_overwrite && !sp_ui_overwrite_file(filename)) {
327         return FALSE;
328     }
330     sp_document_ensure_up_to_date(doc);
332     /* Go to document coordinates */
333     gdouble t = y0;
334     y0 = sp_document_height(doc) - y1;
335     y1 = sp_document_height(doc) - t;
337     /*
338      * 1) a[0] * x0 + a[2] * y1 + a[4] = 0.0
339      * 2) a[1] * x0 + a[3] * y1 + a[5] = 0.0
340      * 3) a[0] * x1 + a[2] * y1 + a[4] = width
341      * 4) a[1] * x0 + a[3] * y0 + a[5] = height
342      * 5) a[1] = 0.0;
343      * 6) a[2] = 0.0;
344      *
345      * (1,3) a[0] * x1 - a[0] * x0 = width
346      * a[0] = width / (x1 - x0)
347      * (2,4) a[3] * y0 - a[3] * y1 = height
348      * a[3] = height / (y0 - y1)
349      * (1) a[4] = -a[0] * x0
350      * (2) a[5] = -a[3] * y1
351      */
353     NRMatrix affine;
354     affine.c[0] = width / (x1 - x0);
355     affine.c[1] = 0.0;
356     affine.c[2] = 0.0;
357     affine.c[3] = height / (y1 - y0);
358     affine.c[4] = -affine.c[0] * x0;
359     affine.c[5] = -affine.c[3] * y0;
361     //SP_PRINT_MATRIX("SVG2PNG", &affine);
363     struct SPEBP ebp;
364     ebp.width  = width;
365     ebp.height = height;
366     ebp.r      = NR_RGBA32_R(bgcolor);
367     ebp.g      = NR_RGBA32_G(bgcolor);
368     ebp.b      = NR_RGBA32_B(bgcolor);
369     ebp.a      = NR_RGBA32_A(bgcolor);
371     /* Create new arena */
372     NRArena *arena = NRArena::create();
373     unsigned dkey = sp_item_display_key_new(1);
375     /* Create ArenaItems and set transform */
376     ebp.root = sp_item_invoke_show(SP_ITEM(sp_document_root(doc)), arena, dkey, SP_ITEM_SHOW_DISPLAY);
377     nr_arena_item_set_transform(NR_ARENA_ITEM(ebp.root), NR::Matrix(&affine));
379     // We show all and then hide all items we don't want, instead of showing only requested items,
380     // because that would not work if the shown item references something in defs
381     if (items_only) {
382         hide_other_items_recursively(sp_document_root(doc), items_only, dkey);
383     }
385     ebp.status = status;
386     ebp.data   = data;
388     if ((width < 256) || ((width * height) < 32768)) {
389         ebp.px = nr_pixelstore_64K_new(FALSE, 0);
390         ebp.sheight = 65536 / (4 * width);
391         write_status = sp_png_write_rgba_striped(filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp);
392         nr_pixelstore_64K_free(ebp.px);
393     } else {
394         ebp.px = g_new(guchar, 4 * 64 * width);
395         ebp.sheight = 64;
396         write_status = sp_png_write_rgba_striped(filename, width, height, xdpi, ydpi, sp_export_get_rows, &ebp);
397         g_free(ebp.px);
398     }
400     // Hide items
401     sp_item_invoke_hide(SP_ITEM(sp_document_root(doc)), dkey);
403     /* Free Arena and ArenaItem */
404     nr_arena_item_unref(ebp.root);
405     nr_object_unref((NRObject *) arena);
406     return write_status;