1 /* save_png.c - save PNG image
3 * Raster graphics library
5 * Copyright (c) 2023 Window Maker Team
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
33 #include "imgformat.h"
37 * Save RImage to PNG image
39 Bool
RSavePNG(RImage
*img
, const char *filename
, char *title
)
43 png_infop png_info_ptr
;
47 int width
= img
->width
;
48 int height
= img
->height
;
50 file
= fopen(filename
, "wb");
52 RErrorCode
= RERR_OPEN
;
56 /* Initialize write structure */
57 png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
58 if (png_ptr
== NULL
) {
60 RErrorCode
= RERR_NOMEMORY
;
64 /* Initialize info structure */
65 png_info_ptr
= png_create_info_struct(png_ptr
);
66 if (png_info_ptr
== NULL
) {
68 RErrorCode
= RERR_NOMEMORY
;
72 /* Setup Exception handling */
73 if (setjmp(png_jmpbuf (png_ptr
))) {
75 RErrorCode
= RERR_INTERNAL
;
79 png_init_io(png_ptr
, file
);
81 /* Write header (8 bit colour depth) */
82 png_set_IHDR(png_ptr
, png_info_ptr
, width
, height
, 8, PNG_COLOR_TYPE_RGB
,
83 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_BASE
,
84 PNG_FILTER_TYPE_BASE
);
86 /* Set title if any */
89 title_text
.compression
= PNG_TEXT_COMPRESSION_NONE
;
90 title_text
.key
= "Title";
91 title_text
.text
= title
;
92 png_set_text(png_ptr
, png_info_ptr
, &title_text
, 1);
95 png_write_info(png_ptr
, png_info_ptr
);
97 /* Allocate memory for one row (3 bytes per pixel - RGB) */
98 png_row
= (png_bytep
) malloc(3 * width
* sizeof(png_byte
));
100 /* Write image data */
101 for (y
= 0; y
< height
; y
++) {
102 for (x
= 0; x
< width
; x
++) {
105 RGetPixel(img
, x
, y
, &pixel
);
106 ptr
= &(png_row
[x
* 3]);
108 ptr
[1] = pixel
.green
;
111 png_write_row(png_ptr
, png_row
);
115 png_write_end(png_ptr
, NULL
);
119 if (png_info_ptr
!= NULL
)
120 png_free_data(png_ptr
, png_info_ptr
, PNG_FREE_ALL
, -1);
122 png_destroy_write_struct(&png_ptr
, (png_infopp
) NULL
);