2 /* example.c - an example of using libpng */
4 /* This is an example of how to use libpng to read and write PNG files.
5 * The file libpng.txt is much more verbose then this. If you have not
6 * read it, do so first. This was designed to be a starting point of an
7 * implementation. This is not officially part of libpng, and therefore
8 * does not require a copyright notice.
10 * This file does not currently compile, because it is missing certain
11 * parts, like allocating memory to hold an image. You will have to
12 * supply these parts to get it to compile. For an example of a minimal
13 * working PNG reader/writer, see pngtest.c, included in this distribution.
16 #include "../png/png.h"
18 /* Check to see if a file is a PNG file using png_sig_cmp(). Returns
19 * non-zero if the image is a PNG, and 0 if it isn't a PNG.
21 * If this call is successful, and you are going to keep the file open,
22 * you should call png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK); once
23 * you have created the png_ptr, so that libpng knows your application
24 * has read that many bytes from the start of the file. Make sure you
25 * don't call png_set_sig_bytes() with more than 8 bytes read or give it
26 * an incorrect number of bytes read, or you will either have read too
27 * many bytes (your fault), or you are telling libpng to read the wrong
28 * number of magic bytes (also your fault).
30 * Many applications already read the first 2 or 4 bytes from the start
31 * of the image to determine the file type, so it would be easiest just
32 * to pass the bytes to png_sig_cmp() or even skip that if you know
33 * you have a PNG file, and call png_set_sig_bytes().
35 #define PNG_BYTES_TO_CHECK 4
36 int check_if_png(char *file_name
, FILE **fp
)
38 char buf
[PNG_BYTES_TO_CHECK
];
40 /* Open the prospective PNG file. */
41 if ((*fp
= fopen(file_name
, "rb")) != NULL
);
44 /* Read in the signature bytes */
45 if (fread(buf
, 1, PNG_BYTES_TO_CHECK
, *fp
) != PNG_BYTES_TO_CHECK
)
48 /* Compare the first PNG_BYTES_TO_CHECK bytes of the signature. */
49 return(png_sig_cmp(buf
, (png_size_t
)0, PNG_BYTES_TO_CHECK
));
52 /* Read a PNG file. You may want to return an error code if the read
53 * fails (depending upon the failure). There are two "prototypes" given
54 * here - one where we are given the filename, and we need to open the
55 * file, and the other where we are given an open file (possibly with
56 * some or all of the magic bytes read - see comments above).
58 #ifdef open_file /* prototype 1 */
59 void read_png(char *file_name
) /* We need to open the file */
63 unsigned int sig_read
= 0;
64 png_uint_32 width
, height
;
65 int bit_depth
, color_type
, interlace_type
;
68 if ((fp
= fopen(file_name
, "rb")) == NULL
)
70 #else no_open_file /* prototype 2 */
71 void read_png(FILE *fp
, unsigned int sig_read
) /* file is already open */
75 png_uint_32 width
, height
;
76 int bit_depth
, color_type
, interlace_type
;
77 #endif no_open_file /* only use one prototype! */
79 /* Create and initialize the png_struct with the desired error handler
80 * functions. If you want to use the default stderr and longjump method,
81 * you can supply NULL for the last three parameters. We also supply the
82 * the compiler header file version, so that we know if the application
83 * was compiled with a compatible version of the library. REQUIRED
85 png_ptr
= png_create_read_struct(PNG_LIBPNG_VER_STRING
,
86 (void *)user_error_ptr
, user_error_fn
, user_warning_fn
);
94 /* Allocate/initialize the memory for image information. REQUIRED. */
95 info_ptr
= png_create_info_struct(png_ptr
);
99 png_destroy_read_struct(&png_ptr
, (png_infopp
)NULL
, (png_infopp
)NULL
);
103 /* Set error handling if you are using the setjmp/longjmp method (this is
104 * the normal method of doing things with libpng). REQUIRED unless you
105 * set up your own error handlers in the png_create_read_struct() earlier.
107 if (setjmp(png_ptr
->jmpbuf
))
109 /* Free all of the memory associated with the png_ptr and info_ptr */
110 png_destroy_read_struct(&png_ptr
, &info_ptr
, (png_infopp
)NULL
);
112 /* If we get here, we had a problem reading the file */
116 /* One of the following I/O initialization methods is REQUIRED */
117 #ifdef streams /* PNG file I/O method 1 */
118 /* Set up the input control if you are using standard C streams */
119 png_init_io(png_ptr
, fp
);
121 #else no_streams /* PNG file I/O method 2 */
122 /* If you are using replacement read functions, instead of calling
123 * png_init_io() here you would call:
125 png_set_read_fn(png_ptr
, (void *)user_io_ptr
, user_read_fn
);
126 /* where user_io_ptr is a structure you want available to the callbacks */
127 #endif no_streams /* Use only one I/O method! */
129 /* If we have already read some of the signature */
130 png_set_sig_bytes(png_ptr
, sig_read
);
132 /* The call to png_read_info() gives us all of the information from the
133 * PNG file before the first IDAT (image data chunk). REQUIRED
135 png_read_info(png_ptr
, info_ptr
);
137 png_get_IHDR(png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
,
138 &interlace_type
, NULL
, NULL
);
140 /**** Set up the data transformations you want. Note that these are all
141 **** optional. Only call them if you want/need them. Many of the
142 **** transformations only work on specific types of images, and many
143 **** are mutually exclusive.
146 /* tell libpng to strip 16 bit/color files down to 8 bits/color */
147 png_set_strip_16(png_ptr
);
149 /* Strip alpha bytes from the input data without combining with th
150 * background (not recommended).
152 png_set_strip_alpha(png_ptr
);
154 /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
155 * byte into separate bytes (useful for paletted and grayscale images).
157 png_set_packing(png_ptr
);
159 /* Change the order of packed pixels to least significant bit first
160 * (not useful if you are using png_set_packing). */
161 png_set_packswap(png_ptr
);
163 /* Expand paletted colors into true RGB triplets */
164 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
165 png_set_expand(png_ptr
);
167 /* Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
168 if (color_type
== PNG_COLOR_TYPE_GRAY
&& bit_depth
< 8)
169 png_set_expand(png_ptr
);
171 /* Expand paletted or RGB images with transparency to full alpha channels
172 * so the data will be available as RGBA quartets.
174 if (png_get_valid(png_ptr
, info_ptr
, PNG_INFO_tRNS
))
175 png_set_expand(png_ptr
);
177 /* Set the background color to draw transparent and alpha images over.
178 * It is possible to set the red, green, and blue components directly
179 * for paletted images instead of supplying a palette index. Note that
180 * even if the PNG file supplies a background, you are not required to
181 * use it - you should use the (solid) application background if it has one.
184 png_color_16 my_background
, *image_background
;
186 if (png_get_bKGD(png_ptr
, info_ptr
, &image_background
))
187 png_set_background(png_ptr
, image_background
,
188 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
190 png_set_background(png_ptr
, &my_background
,
191 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
193 /* Some suggestions as to how to get a screen gamma value */
195 /* Note that screen gamma is (display_gamma/viewing_gamma) */
196 if (/* We have a user-defined screen gamma value */)
198 screen_gamma
= user
-defined screen_gamma
;
200 /* This is one way that applications share the same screen gamma value */
201 else if ((gamma_str
= getenv("SCREEN_GAMMA")) != NULL
)
203 screen_gamma
= atof(gamma_str
);
205 /* If we don't have another value */
208 screen_gamma
= 2.2; /* A good guess for a PC monitors in a dimly
210 screen_gamma
= 1.7 or 1.0; /* A good guess for Mac systems */
213 /* Tell libpng to handle the gamma conversion for you. The second call
214 * is a good guess for PC generated images, but it should be configurable
215 * by the user at run time by the user. It is strongly suggested that
216 * your application support gamma correction.
221 if (png_get_sRGB(png_ptr
, info_ptr
, &intent
))
222 png_set_sRGB(png_ptr
, intent
, 0);
224 if (png_get_gAMA(png_ptr
, info_ptr
, &image_gamma
))
225 png_set_gamma(png_ptr
, screen_gamma
, image_gamma
);
227 png_set_gamma(png_ptr
, screen_gamma
, 0.50);
229 /* Dither RGB files down to 8 bit palette or reduce palettes
230 * to the number of colors available on your screen.
232 if (color_type
& PNG_COLOR_MASK_COLOR
)
234 png_uint_32 num_palette
;
237 /* This reduces the image to the application supplied palette */
238 if (/* we have our own palette */)
240 /* An array of colors to which the image should be dithered */
241 png_color std_color_cube
[MAX_SCREEN_COLORS
];
243 png_set_dither(png_ptr
, std_color_cube
, MAX_SCREEN_COLORS
,
244 MAX_SCREEN_COLORS
, NULL
, 0);
246 /* This reduces the image to the palette supplied in the file */
247 else if (png_get_PLTE(png_ptr
, info_ptr
, &palette
, &num_palette
))
249 png_color16p histogram
;
251 png_get_hIST(png_ptr
, info_ptr
, &histogram
);
253 png_set_dither(png_ptr
, palette
, num_palette
,
254 max_screen_colors
, histogram
, 0);
258 /* invert monocrome files to have 0 as white and 1 as black */
259 png_set_invert_mono(png_ptr
);
261 /* If you want to shift the pixel values from the range [0,255] or
262 * [0,65535] to the original [0,7] or [0,31], or whatever range the
263 * colors were originally in:
265 if (png_get_valid(png_ptr
, info_ptr
, PNG_INFO_sBIT
))
269 png_get_sBIT(png_ptr
, info_ptr
, &sig_bit
);
270 png_set_shift(png_ptr
, sig_bit
);
273 /* flip the RGB pixels to BGR (or RGBA to BGRA) */
274 png_set_bgr(png_ptr
);
276 /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
277 png_set_swap_alpha(png_ptr
);
279 /* swap bytes of 16 bit files to least significant byte first */
280 png_set_swap(png_ptr
);
282 /* Add filler (or alpha) byte (before/after each RGB triplet) */
283 png_set_filler(png_ptr
, 0xff, PNG_FILLER_AFTER
);
285 /* Turn on interlace handling. REQUIRED if you are not using
286 * png_read_image(). To see how to handle interlacing passes,
287 * see the png_read_row() method below:
289 number_passes
= png_set_interlace_handling(png_ptr
);
291 /* Optional call to gamma correct and add the background to the palette
292 * and update info structure. REQUIRED if you are expecting libpng to
293 * update the palette for you (ie you selected such a transform above).
295 png_read_update_info(png_ptr
, info_ptr
);
297 /* Allocate the memory to hold the image using the fields of info_ptr. */
299 /* The easiest way to read the image: */
300 png_bytep row_pointers
[height
];
302 for (row
= 0; row
< height
; row
++)
304 row_pointers
[row
] = malloc(png_get_rowbytes(png_ptr
, info_ptr
));
307 /* Now it's time to read the image. One of these methods is REQUIRED */
308 #ifdef entire /* Read the entire image in one go */
309 png_read_image(png_ptr
, row_pointers
);
311 #else no_entire /* Read the image one or more scanlines at a time */
312 /* The other way to read images - deal with interlacing: */
314 for (pass
= 0; pass
< number_passes
; pass
++)
316 #ifdef single /* Read the image a single row at a time */
317 for (y
= 0; y
< height
; y
++)
319 png_bytep row_pointers
= row
[y
];
320 png_read_rows(png_ptr
, &row_pointers
, NULL
, 1);
323 #else no_single /* Read the image several rows at a time */
324 for (y
= 0; y
< height
; y
+= number_of_rows
)
326 #ifdef sparkle /* Read the image using the "sparkle" effect. */
327 png_read_rows(png_ptr
, row_pointers
, NULL
, number_of_rows
);
329 #else no_sparkle /* Read the image using the "rectangle" effect */
330 png_read_rows(png_ptr
, NULL
, row_pointers
, number_of_rows
);
331 #endif no_sparkle /* use only one of these two methods */
334 /* if you want to display the image after every pass, do
336 #endif no_single /* use only one of these two methods */
338 #endif no_entire /* use only one of these two methods */
340 /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
341 png_read_end(png_ptr
, info_ptr
);
343 /* clean up after the read, and free any memory allocated - REQUIRED */
344 png_destroy_read_struct(&png_ptr
, &info_ptr
, (png_infopp
)NULL
);
353 /* progressively read a file */
356 initialize_png_reader(png_structp
*png_ptr
, png_infop
*info_ptr
)
358 /* Create and initialize the png_struct with the desired error handler
359 * functions. If you want to use the default stderr and longjump method,
360 * you can supply NULL for the last three parameters. We also check that
361 * the library version is compatible in case we are using dynamically
364 *png_ptr
= png_create_read_struct(PNG_LIBPNG_VER_STRING
,
365 (void *)user_error_ptr
, user_error_fn
, user_warning_fn
);
367 if (*png_ptr
== NULL
)
373 *info_ptr
= png_create_info_struct(png_ptr
);
375 if (*info_ptr
== NULL
)
377 png_destroy_read_struct(png_ptr
, info_ptr
, (png_infopp
)NULL
);
381 if (setjmp((*png_ptr
)->jmpbuf
))
383 png_destroy_read_struct(png_ptr
, info_ptr
, (png_infopp
)NULL
);
387 /* this one's new. You will need to provide all three
388 * function callbacks, even if you aren't using them all.
389 * These functions shouldn't be dependent on global or
390 * static variables if you are decoding several images
391 * simultaneously. You should store stream specific data
392 * in a separate struct, given as the second parameter,
393 * and retrieve the pointer from inside the callbacks using
394 * the function png_get_progressive_ptr(png_ptr).
396 png_set_progressive_read_fn(*png_ptr
, (void *)stream_data
,
397 info_callback
, row_callback
, end_callback
);
403 process_data(png_structp
*png_ptr
, png_infop
*info_ptr
,
404 png_bytep buffer
, png_uint_32 length
)
406 if (setjmp((*png_ptr
)->jmpbuf
))
408 /* Free the png_ptr and info_ptr memory on error */
409 png_destroy_read_struct(png_ptr
, info_ptr
, (png_infopp
)NULL
);
413 /* This one's new also. Simply give it chunks of data as
414 * they arrive from the data stream (in order, of course).
415 * On Segmented machines, don't give it any more than 64K.
416 * The library seems to run fine with sizes of 4K, although
417 * you can give it much less if necessary (I assume you can
418 * give it chunks of 1 byte, but I haven't tried with less
419 * than 256 bytes yet). When this function returns, you may
420 * want to display any rows that were generated in the row
421 * callback, if you aren't already displaying them there.
423 png_process_data(*png_ptr
, *info_ptr
, buffer
, length
);
427 info_callback(png_structp png_ptr
, png_infop info
)
429 /* do any setup here, including setting any of the transformations
430 * mentioned in the Reading PNG files section. For now, you _must_
431 * call either png_start_read_image() or png_read_update_info()
432 * after all the transformations are set (even if you don't set
433 * any). You may start getting rows before png_process_data()
434 * returns, so this is your last chance to prepare for that.
438 row_callback(png_structp png_ptr
, png_bytep new_row
,
439 png_uint_32 row_num
, int pass
)
441 /* this function is called for every row in the image. If the
442 * image is interlacing, and you turned on the interlace handler,
443 * this function will be called for every row in every pass.
444 * Some of these rows will not be changed from the previous pass.
445 * When the row is not changed, the new_row variable will be NULL.
446 * The rows and passes are called in order, so you don't really
447 * need the row_num and pass, but I'm supplying them because it
448 * may make your life easier.
450 * For the non-NULL rows of interlaced images, you must call
451 * png_progressive_combine_row() passing in the row and the
452 * old row. You can call this function for NULL rows (it will
453 * just return) and for non-interlaced images (it just does the
454 * memcpy for you) if it will make the code easier. Thus, you
455 * can just do this for all cases:
458 png_progressive_combine_row(png_ptr
, old_row
, new_row
);
460 /* where old_row is what was displayed for previous rows. Note
461 * that the first pass (pass == 0 really) will completely cover
462 * the old row, so the rows do not have to be initialized. After
463 * the first pass (and only for interlaced images), you will have
464 * to pass the current row, and the function will combine the
465 * old row and the new row.
469 end_callback(png_structp png_ptr
, png_infop info
)
471 /* this function is called when the whole image has been read,
472 * including any chunks after the image (up to and including
473 * the IEND). You will usually have the same info chunk as you
474 * had in the header, although some data may have been added
475 * to the comments and time fields.
477 * Most people won't do much here, perhaps setting a flag that
478 * marks the image as finished.
482 /* write a png file */
483 void write_png(char *file_name
/* , ... other image information ... */)
490 fp
= fopen(file_name
, "wb");
494 /* Create and initialize the png_struct with the desired error handler
495 * functions. If you want to use the default stderr and longjump method,
496 * you can supply NULL for the last three parameters. We also check that
497 * the library version is compatible with the one used at compile time,
498 * in case we are using dynamically linked libraries. REQUIRED.
500 png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
,
501 (void *)user_error_ptr
, user_error_fn
, user_warning_fn
);
509 /* Allocate/initialize the image information data. REQUIRED */
510 info_ptr
= png_create_info_struct(png_ptr
);
511 if (info_ptr
== NULL
)
514 png_destroy_write_struct(&png_ptr
, (png_infopp
)NULL
);
518 /* Set error handling. REQUIRED if you aren't supplying your own
519 * error hadnling functions in the png_create_write_struct() call.
521 if (setjmp(png_ptr
->jmpbuf
))
523 /* If we get here, we had a problem reading the file */
525 png_destroy_write_struct(&png_ptr
, (png_infopp
)NULL
);
529 /* One of the following I/O initialization functions is REQUIRED */
530 #ifdef streams /* I/O initialization method 1 */
531 /* set up the output control if you are using standard C streams */
532 png_init_io(png_ptr
, fp
);
533 #else no_streams /* I/O initialization method 2 */
534 /* If you are using replacement read functions, instead of calling
535 * png_init_io() here you would call */
536 png_set_write_fn(png_ptr
, (void *)user_io_ptr
, user_write_fn
,
537 user_IO_flush_function
);
538 /* where user_io_ptr is a structure you want available to the callbacks */
539 #endif no_streams /* only use one initialization method */
541 /* Set the image information here. Width and height are up to 2^31,
542 * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
543 * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
544 * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
545 * or PNG_COLOR_TYPE_RGB_ALPHA. interlace is either PNG_INTERLACE_NONE or
546 * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
547 * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
549 png_set_IHDR(png_ptr
, info_ptr
, width
, height
, bit_depth
, PNG_COLOR_TYPE_
???,
550 PNG_INTERLACE_
????, PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
552 /* set the palette if there is one. REQUIRED for indexed-color images */
553 palette
= (png_colorp
)png_malloc(png_ptr
, 256 * sizeof (png_color
));
554 /* ... set palette colors ... */
555 png_set_PLTE(png_ptr
, info_ptr
, palette
, 256);
557 /* optional significant bit chunk */
558 /* if we are dealing with a grayscale image then */
559 sig_bit
.gray
= true_bit_depth
;
560 /* otherwise, if we are dealing with a color image then */
561 sig_bit
.red
= true_red_bit_depth
;
562 sig_bit
.green
= true_green_bit_depth
;
563 sig_bit
.blue
= true_blue_bit_depth
;
564 /* if the image has an alpha channel then */
565 sig_bit
.alpha
= true_alpha_bit_depth
;
566 png_set_sBIT(png_ptr
, info_ptr
, sig_bit
);
569 /* Optional gamma chunk is strongly suggested if you have any guess
570 * as to the correct gamma of the image.
572 png_set_gAMA(png_ptr
, info_ptr
, gamma
);
574 /* Optionally write comments into the image */
575 text_ptr
[0].key
= "Title";
576 text_ptr
[0].text
= "Mona Lisa";
577 text_ptr
[0].compression
= PNG_TEXT_COMPRESSION_NONE
;
578 text_ptr
[1].key
= "Author";
579 text_ptr
[1].text
= "Leonardo DaVinci";
580 text_ptr
[1].compression
= PNG_TEXT_COMPRESSION_NONE
;
581 text_ptr
[2].key
= "Description";
582 text_ptr
[2].text
= "<long text>";
583 text_ptr
[2].compression
= PNG_TEXT_COMPRESSION_zTXt
;
584 png_set_text(png_ptr
, info_ptr
, text_ptr
, 2);
586 /* other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs, */
587 /* note that if sRGB is present the cHRM chunk must be ignored
588 * on read and must be written in accordance with the sRGB profile */
590 /* Write the file header information. REQUIRED */
591 png_write_info(png_ptr
, info_ptr
);
593 /* Once we write out the header, the compression type on the text
594 * chunks gets changed to PNG_TEXT_COMPRESSION_NONE_WR or
595 * PNG_TEXT_COMPRESSION_zTXt_WR, so it doesn't get written out again
599 /* set up the transformations you want. Note that these are
600 * all optional. Only call them if you want them.
603 /* invert monocrome pixels */
604 png_set_invert_mono(png_ptr
);
606 /* Shift the pixels up to a legal bit depth and fill in
607 * as appropriate to correctly scale the image.
609 png_set_shift(png_ptr
, &sig_bit
);
611 /* pack pixels into bytes */
612 png_set_packing(png_ptr
);
614 /* swap location of alpha bytes from ARGB to RGBA */
615 png_set_swap_alpha(png_ptr
);
617 /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
618 * RGB (4 channels -> 3 channels). The second parameter is not used.
620 png_set_filler(png_ptr
, 0, PNG_FILLER_BEFORE
);
622 /* flip BGR pixels to RGB */
623 png_set_bgr(png_ptr
);
625 /* swap bytes of 16-bit files to most significant byte first */
626 png_set_swap(png_ptr
);
628 /* swap bits of 1, 2, 4 bit packed pixel formats */
629 png_set_packswap(png_ptr
);
631 /* turn on interlace handling if you are not using png_write_image() */
633 number_passes
= png_set_interlace_handling(png_ptr
);
637 /* The easiest way to write the image (you may have a different memory
638 * layout, however, so choose what fits your needs best). You need to
639 * use the first method if you aren't handling interlacing yourself.
641 png_byte row_pointers
[height
][width
];
643 /* One of the following output methods is REQUIRED */
644 #ifdef entire /* write out the entire image data in one call */
645 png_write_image(png_ptr
, row_pointers
);
647 /* the other way to write the image - deal with interlacing */
649 #else no_entire /* write out the image data by one or more scanlines */
650 /* The number of passes is either 1 for non-interlaced images,
651 * or 7 for interlaced images.
653 for (pass
= 0; pass
< number_passes
; pass
++)
655 /* Write a few rows at a time. */
656 png_write_rows(png_ptr
, row_pointers
, number_of_rows
);
658 /* If you are only writing one row at a time, this works */
659 for (y
= 0; y
< height
; y
++)
661 png_bytep row_pointers
= row
[y
];
662 png_write_rows(png_ptr
, &row_pointers
, 1);
665 #endif no_entire /* use only one output method */
667 /* You can write optional chunks like tEXt, zTXt, and tIME at the end
671 /* It is REQUIRED to call this to finish writing the rest of the file */
672 png_write_end(png_ptr
, info_ptr
);
674 /* if you malloced the palette, free it here */
675 free(info_ptr
->palette
);
677 /* if you allocated any text comments, free them here */
679 /* clean up after the write, and free any memory allocated */
680 png_destroy_write_struct(&png_ptr
, (png_infopp
)NULL
);