2 /* pngread.c - read a PNG file
4 * Last changed in libpng 1.6.24 [August 4, 2016]
5 * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
6 * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
7 * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
9 * This code is released under the libpng license.
10 * For conditions of distribution and use, see the disclaimer
11 * and license in png.h
13 * This file contains routines that an application calls directly to
14 * read a PNG file or stream.
18 #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
22 #ifdef PNG_READ_SUPPORTED
24 /* Create a PNG structure for reading, and allocate any memory needed. */
25 PNG_FUNCTION(png_structp,PNGAPI
26 png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
27 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
29 #ifndef PNG_USER_MEM_SUPPORTED
30 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
31 error_fn, warn_fn, NULL, NULL, NULL);
33 return png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
34 warn_fn, NULL, NULL, NULL);
37 /* Alternate create PNG structure for reading, and allocate any memory
40 PNG_FUNCTION(png_structp,PNGAPI
41 png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
42 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
43 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
45 png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
46 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
51 png_ptr->mode = PNG_IS_READ_STRUCT;
53 /* Added in libpng-1.6.0; this can be used to detect a read structure if
54 * required (it will be zero in a write structure.)
56 # ifdef PNG_SEQUENTIAL_READ_SUPPORTED
57 png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE;
60 # ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED
61 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
63 /* In stable builds only warn if an application error can be completely
66 # if PNG_RELEASE_BUILD
67 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
71 /* TODO: delay this, it can be done in png_init_io (if the app doesn't
72 * do it itself) avoiding setting the default function if it is not
75 png_set_read_fn(png_ptr, NULL, NULL);
82 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
83 /* Read the information before the actual image data. This has been
84 * changed in v0.90 to allow reading a file that already has the magic
85 * bytes read from the stream. You can tell libpng how many bytes have
86 * been read from the beginning of the stream (up to the maximum of 8)
87 * via png_set_sig_bytes(), and we will only check the remaining bytes
88 * here. The application can then have access to the signature bytes we
89 * read if it is determined that this isn't a valid PNG file.
92 png_read_info(png_structrp png_ptr, png_inforp info_ptr)
94 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
98 png_debug(1, "in png_read_info");
100 if (png_ptr == NULL || info_ptr == NULL)
103 /* Read and check the PNG file signature. */
104 png_read_sig(png_ptr, info_ptr);
108 png_uint_32 length = png_read_chunk_header(png_ptr);
109 png_uint_32 chunk_name = png_ptr->chunk_name;
111 /* IDAT logic needs to happen here to simplify getting the two flags
114 if (chunk_name == png_IDAT)
116 if ((png_ptr->mode & PNG_HAVE_IHDR) == 0)
117 png_chunk_error(png_ptr, "Missing IHDR before IDAT");
119 else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
120 (png_ptr->mode & PNG_HAVE_PLTE) == 0)
121 png_chunk_error(png_ptr, "Missing PLTE before IDAT");
123 else if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
124 png_chunk_benign_error(png_ptr, "Too many IDATs found");
126 png_ptr->mode |= PNG_HAVE_IDAT;
129 else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
131 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
132 png_ptr->mode |= PNG_AFTER_IDAT;
135 /* This should be a binary subdivision search or a hash for
136 * matching the chunk name rather than a linear search.
138 if (chunk_name == png_IHDR)
139 png_handle_IHDR(png_ptr, info_ptr, length);
141 else if (chunk_name == png_IEND)
142 png_handle_IEND(png_ptr, info_ptr, length);
144 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
145 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
147 png_handle_unknown(png_ptr, info_ptr, length, keep);
149 if (chunk_name == png_PLTE)
150 png_ptr->mode |= PNG_HAVE_PLTE;
152 else if (chunk_name == png_IDAT)
154 png_ptr->idat_size = 0; /* It has been consumed */
159 else if (chunk_name == png_PLTE)
160 png_handle_PLTE(png_ptr, info_ptr, length);
162 else if (chunk_name == png_IDAT)
164 png_ptr->idat_size = length;
168 #ifdef PNG_READ_bKGD_SUPPORTED
169 else if (chunk_name == png_bKGD)
170 png_handle_bKGD(png_ptr, info_ptr, length);
173 #ifdef PNG_READ_cHRM_SUPPORTED
174 else if (chunk_name == png_cHRM)
175 png_handle_cHRM(png_ptr, info_ptr, length);
178 #ifdef PNG_READ_gAMA_SUPPORTED
179 else if (chunk_name == png_gAMA)
180 png_handle_gAMA(png_ptr, info_ptr, length);
183 #ifdef PNG_READ_hIST_SUPPORTED
184 else if (chunk_name == png_hIST)
185 png_handle_hIST(png_ptr, info_ptr, length);
188 #ifdef PNG_READ_oFFs_SUPPORTED
189 else if (chunk_name == png_oFFs)
190 png_handle_oFFs(png_ptr, info_ptr, length);
193 #ifdef PNG_READ_pCAL_SUPPORTED
194 else if (chunk_name == png_pCAL)
195 png_handle_pCAL(png_ptr, info_ptr, length);
198 #ifdef PNG_READ_sCAL_SUPPORTED
199 else if (chunk_name == png_sCAL)
200 png_handle_sCAL(png_ptr, info_ptr, length);
203 #ifdef PNG_READ_pHYs_SUPPORTED
204 else if (chunk_name == png_pHYs)
205 png_handle_pHYs(png_ptr, info_ptr, length);
208 #ifdef PNG_READ_sBIT_SUPPORTED
209 else if (chunk_name == png_sBIT)
210 png_handle_sBIT(png_ptr, info_ptr, length);
213 #ifdef PNG_READ_sRGB_SUPPORTED
214 else if (chunk_name == png_sRGB)
215 png_handle_sRGB(png_ptr, info_ptr, length);
218 #ifdef PNG_READ_iCCP_SUPPORTED
219 else if (chunk_name == png_iCCP)
220 png_handle_iCCP(png_ptr, info_ptr, length);
223 #ifdef PNG_READ_sPLT_SUPPORTED
224 else if (chunk_name == png_sPLT)
225 png_handle_sPLT(png_ptr, info_ptr, length);
228 #ifdef PNG_READ_tEXt_SUPPORTED
229 else if (chunk_name == png_tEXt)
230 png_handle_tEXt(png_ptr, info_ptr, length);
233 #ifdef PNG_READ_tIME_SUPPORTED
234 else if (chunk_name == png_tIME)
235 png_handle_tIME(png_ptr, info_ptr, length);
238 #ifdef PNG_READ_tRNS_SUPPORTED
239 else if (chunk_name == png_tRNS)
240 png_handle_tRNS(png_ptr, info_ptr, length);
243 #ifdef PNG_READ_zTXt_SUPPORTED
244 else if (chunk_name == png_zTXt)
245 png_handle_zTXt(png_ptr, info_ptr, length);
248 #ifdef PNG_READ_iTXt_SUPPORTED
249 else if (chunk_name == png_iTXt)
250 png_handle_iTXt(png_ptr, info_ptr, length);
254 png_handle_unknown(png_ptr, info_ptr, length,
255 PNG_HANDLE_CHUNK_AS_DEFAULT);
258 #endif /* SEQUENTIAL_READ */
260 /* Optional call to update the users info_ptr structure */
262 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
264 png_debug(1, "in png_read_update_info");
268 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
270 png_read_start_row(png_ptr);
272 # ifdef PNG_READ_TRANSFORMS_SUPPORTED
273 png_read_transform_info(png_ptr, info_ptr);
279 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
281 png_app_error(png_ptr,
282 "png_read_update_info/png_start_read_image: duplicate call");
286 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
287 /* Initialize palette, background, etc, after transformations
288 * are set, but before any reading takes place. This allows
289 * the user to obtain a gamma-corrected palette, for example.
290 * If the user doesn't call this, we will do it ourselves.
293 png_start_read_image(png_structrp png_ptr)
295 png_debug(1, "in png_start_read_image");
299 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
300 png_read_start_row(png_ptr);
302 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
304 png_app_error(png_ptr,
305 "png_start_read_image/png_read_update_info: duplicate call");
308 #endif /* SEQUENTIAL_READ */
310 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
311 #ifdef PNG_MNG_FEATURES_SUPPORTED
312 /* Undoes intrapixel differencing,
313 * NOTE: this is apparently only supported in the 'sequential' reader.
316 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
318 png_debug(1, "in png_do_read_intrapixel");
321 (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
324 png_uint_32 row_width = row_info->width;
326 if (row_info->bit_depth == 8)
331 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
334 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
340 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
342 *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
343 *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
346 else if (row_info->bit_depth == 16)
351 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
354 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
360 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
362 png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1);
363 png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3);
364 png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5);
365 png_uint_32 red = (s0 + s1 + 65536) & 0xffff;
366 png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
367 *(rp ) = (png_byte)((red >> 8) & 0xff);
368 *(rp + 1) = (png_byte)(red & 0xff);
369 *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
370 *(rp + 5) = (png_byte)(blue & 0xff);
375 #endif /* MNG_FEATURES */
378 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
380 png_row_info row_info;
385 png_debug2(1, "in png_read_row (row %lu, pass %d)",
386 (unsigned long)png_ptr->row_number, png_ptr->pass);
388 /* png_read_start_row sets the information (in particular iwidth) for this
391 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
392 png_read_start_row(png_ptr);
394 /* 1.5.6: row_info moved out of png_struct to a local here. */
395 row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
396 row_info.color_type = png_ptr->color_type;
397 row_info.bit_depth = png_ptr->bit_depth;
398 row_info.channels = png_ptr->channels;
399 row_info.pixel_depth = png_ptr->pixel_depth;
400 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
402 #ifdef PNG_WARNINGS_SUPPORTED
403 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
405 /* Check for transforms that have been set but were defined out */
406 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
407 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
408 png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
411 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
412 if ((png_ptr->transformations & PNG_FILLER) != 0)
413 png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
416 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
417 !defined(PNG_READ_PACKSWAP_SUPPORTED)
418 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
419 png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
422 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
423 if ((png_ptr->transformations & PNG_PACK) != 0)
424 png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
427 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
428 if ((png_ptr->transformations & PNG_SHIFT) != 0)
429 png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
432 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
433 if ((png_ptr->transformations & PNG_BGR) != 0)
434 png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
437 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
438 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
439 png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
442 #endif /* WARNINGS */
444 #ifdef PNG_READ_INTERLACING_SUPPORTED
445 /* If interlaced and we do not need a new row, combine row and return.
446 * Notice that the pixels we have from previous rows have been transformed
447 * already; we can only combine like with like (transformed or
448 * untransformed) and, because of the libpng API for interlaced images, this
449 * means we must transform before de-interlacing.
451 if (png_ptr->interlaced != 0 &&
452 (png_ptr->transformations & PNG_INTERLACE) != 0)
454 switch (png_ptr->pass)
457 if (png_ptr->row_number & 0x07)
460 png_combine_row(png_ptr, dsp_row, 1/*display*/);
461 png_read_finish_row(png_ptr);
467 if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
470 png_combine_row(png_ptr, dsp_row, 1/*display*/);
472 png_read_finish_row(png_ptr);
478 if ((png_ptr->row_number & 0x07) != 4)
480 if (dsp_row != NULL && (png_ptr->row_number & 4))
481 png_combine_row(png_ptr, dsp_row, 1/*display*/);
483 png_read_finish_row(png_ptr);
489 if ((png_ptr->row_number & 3) || png_ptr->width < 3)
492 png_combine_row(png_ptr, dsp_row, 1/*display*/);
494 png_read_finish_row(png_ptr);
500 if ((png_ptr->row_number & 3) != 2)
502 if (dsp_row != NULL && (png_ptr->row_number & 2))
503 png_combine_row(png_ptr, dsp_row, 1/*display*/);
505 png_read_finish_row(png_ptr);
511 if ((png_ptr->row_number & 1) || png_ptr->width < 2)
514 png_combine_row(png_ptr, dsp_row, 1/*display*/);
516 png_read_finish_row(png_ptr);
523 if ((png_ptr->row_number & 1) == 0)
525 png_read_finish_row(png_ptr);
533 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
534 png_error(png_ptr, "Invalid attempt to read row data");
536 /* Fill the row with IDAT data: */
537 png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
539 if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
541 if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
542 png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
543 png_ptr->prev_row + 1, png_ptr->row_buf[0]);
545 png_error(png_ptr, "bad adaptive filter value");
548 /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
549 * 1.5.6, while the buffer really is this big in current versions of libpng
550 * it may not be in the future, so this was changed just to copy the
553 memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
555 #ifdef PNG_MNG_FEATURES_SUPPORTED
556 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
557 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
559 /* Intrapixel differencing */
560 png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
564 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
565 if (png_ptr->transformations)
566 png_do_read_transformations(png_ptr, &row_info);
569 /* The transformed pixel depth should match the depth now in row_info. */
570 if (png_ptr->transformed_pixel_depth == 0)
572 png_ptr->transformed_pixel_depth = row_info.pixel_depth;
573 if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
574 png_error(png_ptr, "sequential row overflow");
577 else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
578 png_error(png_ptr, "internal sequential row size calculation error");
580 #ifdef PNG_READ_INTERLACING_SUPPORTED
581 /* Expand interlaced rows to full size */
582 if (png_ptr->interlaced != 0 &&
583 (png_ptr->transformations & PNG_INTERLACE) != 0)
585 if (png_ptr->pass < 6)
586 png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
587 png_ptr->transformations);
590 png_combine_row(png_ptr, dsp_row, 1/*display*/);
593 png_combine_row(png_ptr, row, 0/*row*/);
600 png_combine_row(png_ptr, row, -1/*ignored*/);
603 png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
605 png_read_finish_row(png_ptr);
607 if (png_ptr->read_row_fn != NULL)
608 (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
611 #endif /* SEQUENTIAL_READ */
613 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
614 /* Read one or more rows of image data. If the image is interlaced,
615 * and png_set_interlace_handling() has been called, the rows need to
616 * contain the contents of the rows from the previous pass. If the
617 * image has alpha or transparency, and png_handle_alpha()[*] has been
618 * called, the rows contents must be initialized to the contents of the
621 * "row" holds the actual image, and pixels are placed in it
622 * as they arrive. If the image is displayed after each pass, it will
623 * appear to "sparkle" in. "display_row" can be used to display a
624 * "chunky" progressive image, with finer detail added as it becomes
625 * available. If you do not want this "chunky" display, you may pass
626 * NULL for display_row. If you do not want the sparkle display, and
627 * you have not called png_handle_alpha(), you may pass NULL for rows.
628 * If you have called png_handle_alpha(), and the image has either an
629 * alpha channel or a transparency chunk, you must provide a buffer for
630 * rows. In this case, you do not have to provide a display_row buffer
631 * also, but you may. If the image is not interlaced, or if you have
632 * not called png_set_interlace_handling(), the display_row buffer will
633 * be ignored, so pass NULL to it.
635 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
639 png_read_rows(png_structrp png_ptr, png_bytepp row,
640 png_bytepp display_row, png_uint_32 num_rows)
646 png_debug(1, "in png_read_rows");
653 if (rp != NULL && dp != NULL)
654 for (i = 0; i < num_rows; i++)
656 png_bytep rptr = *rp++;
657 png_bytep dptr = *dp++;
659 png_read_row(png_ptr, rptr, dptr);
663 for (i = 0; i < num_rows; i++)
665 png_bytep rptr = *rp;
666 png_read_row(png_ptr, rptr, NULL);
671 for (i = 0; i < num_rows; i++)
673 png_bytep dptr = *dp;
674 png_read_row(png_ptr, NULL, dptr);
678 #endif /* SEQUENTIAL_READ */
680 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
681 /* Read the entire image. If the image has an alpha channel or a tRNS
682 * chunk, and you have called png_handle_alpha()[*], you will need to
683 * initialize the image to the current image that PNG will be overlaying.
684 * We set the num_rows again here, in case it was incorrectly set in
685 * png_read_start_row() by a call to png_read_update_info() or
686 * png_start_read_image() if png_set_interlace_handling() wasn't called
687 * prior to either of these functions like it should have been. You can
688 * only call this function once. If you desire to have an image for
689 * each pass of a interlaced image, use png_read_rows() instead.
691 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
694 png_read_image(png_structrp png_ptr, png_bytepp image)
696 png_uint_32 i, image_height;
700 png_debug(1, "in png_read_image");
705 #ifdef PNG_READ_INTERLACING_SUPPORTED
706 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
708 pass = png_set_interlace_handling(png_ptr);
709 /* And make sure transforms are initialized. */
710 png_start_read_image(png_ptr);
714 if (png_ptr->interlaced != 0 &&
715 (png_ptr->transformations & PNG_INTERLACE) == 0)
717 /* Caller called png_start_read_image or png_read_update_info without
718 * first turning on the PNG_INTERLACE transform. We can fix this here,
719 * but the caller should do it!
721 png_warning(png_ptr, "Interlace handling should be turned on when "
722 "using png_read_image");
723 /* Make sure this is set correctly */
724 png_ptr->num_rows = png_ptr->height;
727 /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
728 * the above error case.
730 pass = png_set_interlace_handling(png_ptr);
733 if (png_ptr->interlaced)
735 "Cannot read interlaced image -- interlace handler disabled");
740 image_height=png_ptr->height;
742 for (j = 0; j < pass; j++)
745 for (i = 0; i < image_height; i++)
747 png_read_row(png_ptr, *rp, NULL);
752 #endif /* SEQUENTIAL_READ */
754 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
755 /* Read the end of the PNG file. Will not read past the end of the
756 * file, will verify the end is accurate, and will read any comments
757 * or time information at the end of the file, if info is not NULL.
760 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
762 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
766 png_debug(1, "in png_read_end");
771 /* If png_read_end is called in the middle of reading the rows there may
772 * still be pending IDAT data and an owned zstream. Deal with this here.
774 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
775 if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
777 png_read_finish_IDAT(png_ptr);
779 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
780 /* Report invalid palette index; added at libng-1.5.10 */
781 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
782 png_ptr->num_palette_max > png_ptr->num_palette)
783 png_benign_error(png_ptr, "Read palette index exceeding num_palette");
788 png_uint_32 length = png_read_chunk_header(png_ptr);
789 png_uint_32 chunk_name = png_ptr->chunk_name;
791 if (chunk_name != png_IDAT)
792 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
794 if (chunk_name == png_IEND)
795 png_handle_IEND(png_ptr, info_ptr, length);
797 else if (chunk_name == png_IHDR)
798 png_handle_IHDR(png_ptr, info_ptr, length);
800 else if (info_ptr == NULL)
801 png_crc_finish(png_ptr, length);
803 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
804 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
806 if (chunk_name == png_IDAT)
808 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
809 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
810 png_benign_error(png_ptr, ".Too many IDATs found");
812 png_handle_unknown(png_ptr, info_ptr, length, keep);
813 if (chunk_name == png_PLTE)
814 png_ptr->mode |= PNG_HAVE_PLTE;
818 else if (chunk_name == png_IDAT)
820 /* Zero length IDATs are legal after the last IDAT has been
821 * read, but not after other chunks have been read. 1.6 does not
822 * always read all the deflate data; specifically it cannot be relied
823 * upon to read the Adler32 at the end. If it doesn't ignore IDAT
824 * chunks which are longer than zero as well:
826 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
827 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
828 png_benign_error(png_ptr, "..Too many IDATs found");
830 png_crc_finish(png_ptr, length);
832 else if (chunk_name == png_PLTE)
833 png_handle_PLTE(png_ptr, info_ptr, length);
835 #ifdef PNG_READ_bKGD_SUPPORTED
836 else if (chunk_name == png_bKGD)
837 png_handle_bKGD(png_ptr, info_ptr, length);
840 #ifdef PNG_READ_cHRM_SUPPORTED
841 else if (chunk_name == png_cHRM)
842 png_handle_cHRM(png_ptr, info_ptr, length);
845 #ifdef PNG_READ_gAMA_SUPPORTED
846 else if (chunk_name == png_gAMA)
847 png_handle_gAMA(png_ptr, info_ptr, length);
850 #ifdef PNG_READ_hIST_SUPPORTED
851 else if (chunk_name == png_hIST)
852 png_handle_hIST(png_ptr, info_ptr, length);
855 #ifdef PNG_READ_oFFs_SUPPORTED
856 else if (chunk_name == png_oFFs)
857 png_handle_oFFs(png_ptr, info_ptr, length);
860 #ifdef PNG_READ_pCAL_SUPPORTED
861 else if (chunk_name == png_pCAL)
862 png_handle_pCAL(png_ptr, info_ptr, length);
865 #ifdef PNG_READ_sCAL_SUPPORTED
866 else if (chunk_name == png_sCAL)
867 png_handle_sCAL(png_ptr, info_ptr, length);
870 #ifdef PNG_READ_pHYs_SUPPORTED
871 else if (chunk_name == png_pHYs)
872 png_handle_pHYs(png_ptr, info_ptr, length);
875 #ifdef PNG_READ_sBIT_SUPPORTED
876 else if (chunk_name == png_sBIT)
877 png_handle_sBIT(png_ptr, info_ptr, length);
880 #ifdef PNG_READ_sRGB_SUPPORTED
881 else if (chunk_name == png_sRGB)
882 png_handle_sRGB(png_ptr, info_ptr, length);
885 #ifdef PNG_READ_iCCP_SUPPORTED
886 else if (chunk_name == png_iCCP)
887 png_handle_iCCP(png_ptr, info_ptr, length);
890 #ifdef PNG_READ_sPLT_SUPPORTED
891 else if (chunk_name == png_sPLT)
892 png_handle_sPLT(png_ptr, info_ptr, length);
895 #ifdef PNG_READ_tEXt_SUPPORTED
896 else if (chunk_name == png_tEXt)
897 png_handle_tEXt(png_ptr, info_ptr, length);
900 #ifdef PNG_READ_tIME_SUPPORTED
901 else if (chunk_name == png_tIME)
902 png_handle_tIME(png_ptr, info_ptr, length);
905 #ifdef PNG_READ_tRNS_SUPPORTED
906 else if (chunk_name == png_tRNS)
907 png_handle_tRNS(png_ptr, info_ptr, length);
910 #ifdef PNG_READ_zTXt_SUPPORTED
911 else if (chunk_name == png_zTXt)
912 png_handle_zTXt(png_ptr, info_ptr, length);
915 #ifdef PNG_READ_iTXt_SUPPORTED
916 else if (chunk_name == png_iTXt)
917 png_handle_iTXt(png_ptr, info_ptr, length);
921 png_handle_unknown(png_ptr, info_ptr, length,
922 PNG_HANDLE_CHUNK_AS_DEFAULT);
923 } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
925 #endif /* SEQUENTIAL_READ */
927 /* Free all memory used in the read struct */
929 png_read_destroy(png_structrp png_ptr)
931 png_debug(1, "in png_read_destroy");
933 #ifdef PNG_READ_GAMMA_SUPPORTED
934 png_destroy_gamma_table(png_ptr);
937 png_free(png_ptr, png_ptr->big_row_buf);
938 png_ptr->big_row_buf = NULL;
939 png_free(png_ptr, png_ptr->big_prev_row);
940 png_ptr->big_prev_row = NULL;
941 png_free(png_ptr, png_ptr->read_buffer);
942 png_ptr->read_buffer = NULL;
944 #ifdef PNG_READ_QUANTIZE_SUPPORTED
945 png_free(png_ptr, png_ptr->palette_lookup);
946 png_ptr->palette_lookup = NULL;
947 png_free(png_ptr, png_ptr->quantize_index);
948 png_ptr->quantize_index = NULL;
951 if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
953 png_zfree(png_ptr, png_ptr->palette);
954 png_ptr->palette = NULL;
956 png_ptr->free_me &= ~PNG_FREE_PLTE;
958 #if defined(PNG_tRNS_SUPPORTED) || \
959 defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
960 if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
962 png_free(png_ptr, png_ptr->trans_alpha);
963 png_ptr->trans_alpha = NULL;
965 png_ptr->free_me &= ~PNG_FREE_TRNS;
968 inflateEnd(&png_ptr->zstream);
970 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
971 png_free(png_ptr, png_ptr->save_buffer);
972 png_ptr->save_buffer = NULL;
975 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
976 defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
977 png_free(png_ptr, png_ptr->unknown_chunk.data);
978 png_ptr->unknown_chunk.data = NULL;
981 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
982 png_free(png_ptr, png_ptr->chunk_list);
983 png_ptr->chunk_list = NULL;
986 /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
987 * callbacks are still set at this point. They are required to complete the
988 * destruction of the png_struct itself.
992 /* Free all memory used by the read */
994 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
995 png_infopp end_info_ptr_ptr)
997 png_structrp png_ptr = NULL;
999 png_debug(1, "in png_destroy_read_struct");
1001 if (png_ptr_ptr != NULL)
1002 png_ptr = *png_ptr_ptr;
1004 if (png_ptr == NULL)
1007 /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1008 * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1009 * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1011 png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1012 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1014 *png_ptr_ptr = NULL;
1015 png_read_destroy(png_ptr);
1016 png_destroy_png_struct(png_ptr);
1020 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1022 if (png_ptr == NULL)
1025 png_ptr->read_row_fn = read_row_fn;
1029 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1030 #ifdef PNG_INFO_IMAGE_SUPPORTED
1032 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1033 int transforms, voidp params)
1035 if (png_ptr == NULL || info_ptr == NULL)
1038 /* png_read_info() gives us all of the information from the
1039 * PNG file before the first IDAT (image data chunk).
1041 png_read_info(png_ptr, info_ptr);
1042 if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1043 png_error(png_ptr, "Image is too high to process with png_read_png()");
1045 /* -------------- image transformations start here ------------------- */
1046 /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1047 * is not implemented. This will only happen in de-configured (non-default)
1048 * libpng builds. The results can be unexpected - png_read_png may return
1049 * short or mal-formed rows because the transform is skipped.
1052 /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1054 if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1055 /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1056 * did in earlier versions, while "scale_16" is now more accurate.
1058 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1059 png_set_scale_16(png_ptr);
1061 png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1064 /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1065 * latter by doing SCALE first. This is ok and allows apps not to check for
1066 * which is supported to get the right answer.
1068 if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1069 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1070 png_set_strip_16(png_ptr);
1072 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1075 /* Strip alpha bytes from the input data without combining with
1076 * the background (not recommended).
1078 if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1079 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1080 png_set_strip_alpha(png_ptr);
1082 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1085 /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1086 * byte into separate bytes (useful for paletted and grayscale images).
1088 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1089 #ifdef PNG_READ_PACK_SUPPORTED
1090 png_set_packing(png_ptr);
1092 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1095 /* Change the order of packed pixels to least significant bit first
1096 * (not useful if you are using png_set_packing).
1098 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1099 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1100 png_set_packswap(png_ptr);
1102 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1105 /* Expand paletted colors into true RGB triplets
1106 * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1107 * Expand paletted or RGB images with transparency to full alpha
1108 * channels so the data will be available as RGBA quartets.
1110 if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1111 #ifdef PNG_READ_EXPAND_SUPPORTED
1112 png_set_expand(png_ptr);
1114 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1117 /* We don't handle background color or gamma transformation or quantizing.
1120 /* Invert monochrome files to have 0 as white and 1 as black
1122 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1123 #ifdef PNG_READ_INVERT_SUPPORTED
1124 png_set_invert_mono(png_ptr);
1126 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1129 /* If you want to shift the pixel values from the range [0,255] or
1130 * [0,65535] to the original [0,7] or [0,31], or whatever range the
1131 * colors were originally in:
1133 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1134 #ifdef PNG_READ_SHIFT_SUPPORTED
1135 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1136 png_set_shift(png_ptr, &info_ptr->sig_bit);
1138 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1141 /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1142 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1143 #ifdef PNG_READ_BGR_SUPPORTED
1144 png_set_bgr(png_ptr);
1146 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1149 /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1150 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1151 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1152 png_set_swap_alpha(png_ptr);
1154 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1157 /* Swap bytes of 16-bit files to least significant byte first */
1158 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1159 #ifdef PNG_READ_SWAP_SUPPORTED
1160 png_set_swap(png_ptr);
1162 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1165 /* Added at libpng-1.2.41 */
1166 /* Invert the alpha channel from opacity to transparency */
1167 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1168 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1169 png_set_invert_alpha(png_ptr);
1171 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1174 /* Added at libpng-1.2.41 */
1175 /* Expand grayscale image to RGB */
1176 if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1177 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1178 png_set_gray_to_rgb(png_ptr);
1180 png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1183 /* Added at libpng-1.5.4 */
1184 if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1185 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1186 png_set_expand_16(png_ptr);
1188 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1191 /* We don't handle adding filler bytes */
1193 /* We use png_read_image and rely on that for interlace handling, but we also
1194 * call png_read_update_info therefore must turn on interlace handling now:
1196 (void)png_set_interlace_handling(png_ptr);
1198 /* Optional call to gamma correct and add the background to the palette
1199 * and update info structure. REQUIRED if you are expecting libpng to
1200 * update the palette for you (i.e., you selected such a transform above).
1202 png_read_update_info(png_ptr, info_ptr);
1204 /* -------------- image transformations end here ------------------- */
1206 png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1207 if (info_ptr->row_pointers == NULL)
1211 info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1212 info_ptr->height * (sizeof (png_bytep))));
1214 for (iptr=0; iptr<info_ptr->height; iptr++)
1215 info_ptr->row_pointers[iptr] = NULL;
1217 info_ptr->free_me |= PNG_FREE_ROWS;
1219 for (iptr = 0; iptr < info_ptr->height; iptr++)
1220 info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1221 png_malloc(png_ptr, info_ptr->rowbytes));
1224 png_read_image(png_ptr, info_ptr->row_pointers);
1225 info_ptr->valid |= PNG_INFO_IDAT;
1227 /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1228 png_read_end(png_ptr, info_ptr);
1232 #endif /* INFO_IMAGE */
1233 #endif /* SEQUENTIAL_READ */
1235 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1238 * This code currently relies on the sequential reader, though it could easily
1239 * be made to work with the progressive one.
1241 /* Arguments to png_image_finish_read: */
1243 /* Encoding of PNG data (used by the color-map code) */
1244 # define P_NOTSET 0 /* File encoding not yet known */
1245 # define P_sRGB 1 /* 8-bit encoded to sRGB gamma */
1246 # define P_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1247 # define P_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */
1248 # define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1250 /* Color-map processing: after libpng has run on the PNG image further
1251 * processing may be needed to convert the data to color-map indices.
1253 #define PNG_CMAP_NONE 0
1254 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */
1255 #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */
1256 #define PNG_CMAP_RGB 3 /* Process RGB data */
1257 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1259 /* The following document where the background is for each processing case. */
1260 #define PNG_CMAP_NONE_BACKGROUND 256
1261 #define PNG_CMAP_GA_BACKGROUND 231
1262 #define PNG_CMAP_TRANS_BACKGROUND 254
1263 #define PNG_CMAP_RGB_BACKGROUND 256
1264 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1271 png_int_32 row_stride;
1273 png_const_colorp background;
1274 /* Local variables: */
1275 png_voidp local_row;
1276 png_voidp first_row;
1277 ptrdiff_t row_bytes; /* step between rows */
1278 int file_encoding; /* E_ values above */
1279 png_fixed_point gamma_to_linear; /* For P_FILE, reciprocal of gamma */
1280 int colormap_processing; /* PNG_CMAP_ values above */
1281 } png_image_read_control;
1283 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1284 * called, so setting up the jmp_buf is not required. This means that anything
1285 * called from here must *not* call png_malloc - it has to call png_malloc_warn
1286 * instead so that control is returned safely back to this routine.
1289 png_image_read_init(png_imagep image)
1291 if (image->opaque == NULL)
1293 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1294 png_safe_error, png_safe_warning);
1296 /* And set the rest of the structure to NULL to ensure that the various
1297 * fields are consistent.
1299 memset(image, 0, (sizeof *image));
1300 image->version = PNG_IMAGE_VERSION;
1302 if (png_ptr != NULL)
1304 png_infop info_ptr = png_create_info_struct(png_ptr);
1306 if (info_ptr != NULL)
1308 png_controlp control = png_voidcast(png_controlp,
1309 png_malloc_warn(png_ptr, (sizeof *control)));
1311 if (control != NULL)
1313 memset(control, 0, (sizeof *control));
1315 control->png_ptr = png_ptr;
1316 control->info_ptr = info_ptr;
1317 control->for_write = 0;
1319 image->opaque = control;
1323 /* Error clean up */
1324 png_destroy_info_struct(png_ptr, &info_ptr);
1327 png_destroy_read_struct(&png_ptr, NULL, NULL);
1330 return png_image_error(image, "png_image_read: out of memory");
1333 return png_image_error(image, "png_image_read: opaque pointer not NULL");
1336 /* Utility to find the base format of a PNG file from a png_struct. */
1338 png_image_format(png_structrp png_ptr)
1340 png_uint_32 format = 0;
1342 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1343 format |= PNG_FORMAT_FLAG_COLOR;
1345 if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1346 format |= PNG_FORMAT_FLAG_ALPHA;
1348 /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1349 * sets the png_struct fields; that's all we are interested in here. The
1350 * precise interaction with an app call to png_set_tRNS and PNG file reading
1353 else if (png_ptr->num_trans > 0)
1354 format |= PNG_FORMAT_FLAG_ALPHA;
1356 if (png_ptr->bit_depth == 16)
1357 format |= PNG_FORMAT_FLAG_LINEAR;
1359 if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1360 format |= PNG_FORMAT_FLAG_COLORMAP;
1365 /* Is the given gamma significantly different from sRGB? The test is the same
1366 * one used in pngrtran.c when deciding whether to do gamma correction. The
1367 * arithmetic optimizes the division by using the fact that the inverse of the
1368 * file sRGB gamma is 2.2
1371 png_gamma_not_sRGB(png_fixed_point g)
1375 /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1379 return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1385 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1386 * header and fill in all the information. This is executed in a safe context,
1387 * unlike the init routine above.
1390 png_image_read_header(png_voidp argument)
1392 png_imagep image = png_voidcast(png_imagep, argument);
1393 png_structrp png_ptr = image->opaque->png_ptr;
1394 png_inforp info_ptr = image->opaque->info_ptr;
1396 png_set_benign_errors(png_ptr, 1/*warn*/);
1397 png_read_info(png_ptr, info_ptr);
1399 /* Do this the fast way; just read directly out of png_struct. */
1400 image->width = png_ptr->width;
1401 image->height = png_ptr->height;
1404 png_uint_32 format = png_image_format(png_ptr);
1406 image->format = format;
1408 #ifdef PNG_COLORSPACE_SUPPORTED
1409 /* Does the colorspace match sRGB? If there is no color endpoint
1410 * (colorant) information assume yes, otherwise require the
1411 * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set. If the
1412 * colorspace has been determined to be invalid ignore it.
1414 if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1415 & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1416 PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1417 image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1421 /* We need the maximum number of entries regardless of the format the
1422 * application sets here.
1425 png_uint_32 cmap_entries;
1427 switch (png_ptr->color_type)
1429 case PNG_COLOR_TYPE_GRAY:
1430 cmap_entries = 1U << png_ptr->bit_depth;
1433 case PNG_COLOR_TYPE_PALETTE:
1434 cmap_entries = png_ptr->num_palette;
1442 if (cmap_entries > 256)
1445 image->colormap_entries = cmap_entries;
1451 #ifdef PNG_STDIO_SUPPORTED
1453 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1455 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1459 if (png_image_read_init(image) != 0)
1461 /* This is slightly evil, but png_init_io doesn't do anything other
1462 * than this and we haven't changed the standard IO functions so
1463 * this saves a 'safe' function.
1465 image->opaque->png_ptr->io_ptr = file;
1466 return png_safe_execute(image, png_image_read_header, image);
1471 return png_image_error(image,
1472 "png_image_begin_read_from_stdio: invalid argument");
1475 else if (image != NULL)
1476 return png_image_error(image,
1477 "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1483 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1485 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1487 if (file_name != NULL)
1489 FILE *fp = fopen(file_name, "rb");
1493 if (png_image_read_init(image) != 0)
1495 image->opaque->png_ptr->io_ptr = fp;
1496 image->opaque->owned_file = 1;
1497 return png_safe_execute(image, png_image_read_header, image);
1500 /* Clean up: just the opened file. */
1505 return png_image_error(image, strerror(errno));
1509 return png_image_error(image,
1510 "png_image_begin_read_from_file: invalid argument");
1513 else if (image != NULL)
1514 return png_image_error(image,
1515 "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1521 static void PNGCBAPI
1522 png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need)
1524 if (png_ptr != NULL)
1526 png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1529 png_controlp cp = image->opaque;
1532 png_const_bytep memory = cp->memory;
1533 png_size_t size = cp->size;
1535 if (memory != NULL && size >= need)
1537 memcpy(out, memory, need);
1538 cp->memory = memory + need;
1539 cp->size = size - need;
1543 png_error(png_ptr, "read beyond end of data");
1547 png_error(png_ptr, "invalid memory read");
1551 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1552 png_const_voidp memory, png_size_t size)
1554 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1556 if (memory != NULL && size > 0)
1558 if (png_image_read_init(image) != 0)
1560 /* Now set the IO functions to read from the memory buffer and
1561 * store it into io_ptr. Again do this in-place to avoid calling a
1562 * libpng function that requires error handling.
1564 image->opaque->memory = png_voidcast(png_const_bytep, memory);
1565 image->opaque->size = size;
1566 image->opaque->png_ptr->io_ptr = image;
1567 image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1569 return png_safe_execute(image, png_image_read_header, image);
1574 return png_image_error(image,
1575 "png_image_begin_read_from_memory: invalid argument");
1578 else if (image != NULL)
1579 return png_image_error(image,
1580 "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1585 /* Utility function to skip chunks that are not used by the simplified image
1586 * read functions and an appropriate macro to call it.
1588 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1590 png_image_skip_unused_chunks(png_structrp png_ptr)
1592 /* Prepare the reader to ignore all recognized chunks whose data will not
1593 * be used, i.e., all chunks recognized by libpng except for those
1594 * involved in basic image reading:
1596 * IHDR, PLTE, IDAT, IEND
1598 * Or image data handling:
1600 * tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1602 * This provides a small performance improvement and eliminates any
1603 * potential vulnerability to security problems in the unused chunks.
1605 * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1606 * too. This allows the simplified API to be compiled without iCCP support,
1607 * however if the support is there the chunk is still checked to detect
1608 * errors (which are unfortunately quite common.)
1611 static PNG_CONST png_byte chunks_to_process[] = {
1612 98, 75, 71, 68, '\0', /* bKGD */
1613 99, 72, 82, 77, '\0', /* cHRM */
1614 103, 65, 77, 65, '\0', /* gAMA */
1615 # ifdef PNG_READ_iCCP_SUPPORTED
1616 105, 67, 67, 80, '\0', /* iCCP */
1618 115, 66, 73, 84, '\0', /* sBIT */
1619 115, 82, 71, 66, '\0', /* sRGB */
1622 /* Ignore unknown chunks and all other chunks except for the
1623 * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1625 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1628 /* But do not ignore image data handling chunks */
1629 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1630 chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1634 # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1636 # define PNG_SKIP_CHUNKS(p) ((void)0)
1637 #endif /* HANDLE_AS_UNKNOWN */
1639 /* The following macro gives the exact rounded answer for all values in the
1640 * range 0..255 (it actually divides by 51.2, but the rounding still generates
1641 * the correct numbers 0..5
1643 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1645 /* Utility functions to make particular color-maps */
1647 set_file_encoding(png_image_read_control *display)
1649 png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1650 if (png_gamma_significant(g) != 0)
1652 if (png_gamma_not_sRGB(g) != 0)
1654 display->file_encoding = P_FILE;
1655 display->gamma_to_linear = png_reciprocal(g);
1659 display->file_encoding = P_sRGB;
1663 display->file_encoding = P_LINEAR8;
1667 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1669 if (encoding == P_FILE) /* double check */
1670 encoding = display->file_encoding;
1672 if (encoding == P_NOTSET) /* must be the file encoding */
1674 set_file_encoding(display);
1675 encoding = display->file_encoding;
1681 value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1685 value = png_sRGB_table[value];
1697 png_error(display->image->opaque->png_ptr,
1698 "unexpected encoding (internal error)");
1706 png_colormap_compose(png_image_read_control *display,
1707 png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1708 png_uint_32 background, int encoding)
1710 /* The file value is composed on the background, the background has the given
1711 * encoding and so does the result, the file is encoded with P_FILE and the
1712 * file and alpha are 8-bit values. The (output) encoding will always be
1713 * P_LINEAR or P_sRGB.
1715 png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1716 png_uint_32 b = decode_gamma(display, background, encoding);
1718 /* The alpha is always an 8-bit value (it comes from the palette), the value
1719 * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1721 f = f * alpha + b * (255-alpha);
1723 if (encoding == P_LINEAR)
1725 /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1726 * accurate, it divides by 255.00000005937181414556, with no overflow.)
1728 f *= 257; /* Now scaled by 65535 */
1730 f = (f+32768) >> 16;
1734 f = PNG_sRGB_FROM_LINEAR(f);
1739 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1743 png_create_colormap_entry(png_image_read_control *display,
1744 png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1745 png_uint_32 alpha, int encoding)
1747 png_imagep image = display->image;
1748 const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1750 const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1751 (red != green || green != blue);
1754 png_error(image->opaque->png_ptr, "color-map index out of range");
1756 /* Update the cache with whether the file gamma is significantly different
1759 if (encoding == P_FILE)
1761 if (display->file_encoding == P_NOTSET)
1762 set_file_encoding(display);
1764 /* Note that the cached value may be P_FILE too, but if it is then the
1765 * gamma_to_linear member has been set.
1767 encoding = display->file_encoding;
1770 if (encoding == P_FILE)
1772 png_fixed_point g = display->gamma_to_linear;
1774 red = png_gamma_16bit_correct(red*257, g);
1775 green = png_gamma_16bit_correct(green*257, g);
1776 blue = png_gamma_16bit_correct(blue*257, g);
1778 if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1781 encoding = P_LINEAR;
1786 red = PNG_sRGB_FROM_LINEAR(red * 255);
1787 green = PNG_sRGB_FROM_LINEAR(green * 255);
1788 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1793 else if (encoding == P_LINEAR8)
1795 /* This encoding occurs quite frequently in test cases because PngSuite
1796 * includes a gAMA 1.0 chunk with most images.
1802 encoding = P_LINEAR;
1805 else if (encoding == P_sRGB &&
1806 (convert_to_Y != 0 || output_encoding == P_LINEAR))
1808 /* The values are 8-bit sRGB values, but must be converted to 16-bit
1811 red = png_sRGB_table[red];
1812 green = png_sRGB_table[green];
1813 blue = png_sRGB_table[blue];
1815 encoding = P_LINEAR;
1818 /* This is set if the color isn't gray but the output is. */
1819 if (encoding == P_LINEAR)
1821 if (convert_to_Y != 0)
1823 /* NOTE: these values are copied from png_do_rgb_to_gray */
1824 png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green +
1825 (png_uint_32)2366 * blue;
1827 if (output_encoding == P_LINEAR)
1828 y = (y + 16384) >> 15;
1832 /* y is scaled by 32768, we need it scaled by 255: */
1835 y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1836 alpha = PNG_DIV257(alpha);
1840 blue = red = green = y;
1843 else if (output_encoding == P_sRGB)
1845 red = PNG_sRGB_FROM_LINEAR(red * 255);
1846 green = PNG_sRGB_FROM_LINEAR(green * 255);
1847 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1848 alpha = PNG_DIV257(alpha);
1853 if (encoding != output_encoding)
1854 png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1856 /* Store the value. */
1858 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
1859 const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1860 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
1864 # ifdef PNG_FORMAT_BGR_SUPPORTED
1865 const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1870 if (output_encoding == P_LINEAR)
1872 png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
1874 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1876 /* The linear 16-bit values must be pre-multiplied by the alpha channel
1877 * value, if less than 65535 (this is, effectively, composite on black
1878 * if the alpha channel is removed.)
1880 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1883 entry[afirst ? 0 : 3] = (png_uint_16)alpha;
1891 blue = (blue * alpha + 32767U)/65535U;
1892 green = (green * alpha + 32767U)/65535U;
1893 red = (red * alpha + 32767U)/65535U;
1897 red = green = blue = 0;
1899 entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
1900 entry[afirst + 1] = (png_uint_16)green;
1901 entry[afirst + bgr] = (png_uint_16)red;
1905 entry[1 ^ afirst] = (png_uint_16)alpha;
1912 green = (green * alpha + 32767U)/65535U;
1917 entry[afirst] = (png_uint_16)green;
1925 else /* output encoding is P_sRGB */
1927 png_bytep entry = png_voidcast(png_bytep, display->colormap);
1929 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
1931 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
1934 entry[afirst ? 0 : 3] = (png_byte)alpha;
1936 entry[afirst + (2 ^ bgr)] = (png_byte)blue;
1937 entry[afirst + 1] = (png_byte)green;
1938 entry[afirst + bgr] = (png_byte)red;
1942 entry[1 ^ afirst] = (png_byte)alpha;
1944 entry[afirst] = (png_byte)green;
1962 make_gray_file_colormap(png_image_read_control *display)
1966 for (i=0; i<256; ++i)
1967 png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
1973 make_gray_colormap(png_image_read_control *display)
1977 for (i=0; i<256; ++i)
1978 png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
1982 #define PNG_GRAY_COLORMAP_ENTRIES 256
1985 make_ga_colormap(png_image_read_control *display)
1989 /* Alpha is retained, the output will be a color-map with entries
1990 * selected by six levels of alpha. One transparent entry, 6 gray
1991 * levels for all the intermediate alpha values, leaving 230 entries
1992 * for the opaque grays. The color-map entries are the six values
1993 * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
1996 * if (alpha > 229) // opaque
1998 * // The 231 entries are selected to make the math below work:
2000 * entry = (231 * gray + 128) >> 8;
2002 * else if (alpha < 26) // transparent
2007 * else // partially opaque
2009 * base = 226 + 6 * PNG_DIV51(alpha);
2010 * entry = PNG_DIV51(gray);
2016 unsigned int gray = (i * 256 + 115) / 231;
2017 png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2020 /* 255 is used here for the component values for consistency with the code
2021 * that undoes premultiplication in pngwrite.c.
2023 png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2030 png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2037 #define PNG_GA_COLORMAP_ENTRIES 256
2040 make_rgb_colormap(png_image_read_control *display)
2044 /* Build a 6x6x6 opaque RGB cube */
2045 for (i=r=0; r<6; ++r)
2054 png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2062 #define PNG_RGB_COLORMAP_ENTRIES 216
2064 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2065 #define PNG_RGB_INDEX(r,g,b) \
2066 ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2069 png_image_read_colormap(png_voidp argument)
2071 png_image_read_control *display =
2072 png_voidcast(png_image_read_control*, argument);
2073 const png_imagep image = display->image;
2075 const png_structrp png_ptr = image->opaque->png_ptr;
2076 const png_uint_32 output_format = image->format;
2077 const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2080 unsigned int cmap_entries;
2081 unsigned int output_processing; /* Output processing option */
2082 unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2084 /* Background information; the background color and the index of this color
2085 * in the color-map if it exists (else 256).
2087 unsigned int background_index = 256;
2088 png_uint_32 back_r, back_g, back_b;
2090 /* Flags to accumulate things that need to be done to the input. */
2091 int expand_tRNS = 0;
2093 /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2094 * very difficult to do, the results look awful, and it is difficult to see
2095 * what possible use it is because the application can't control the
2098 if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2099 png_ptr->num_trans > 0) /* alpha in input */ &&
2100 ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2102 if (output_encoding == P_LINEAR) /* compose on black */
2103 back_b = back_g = back_r = 0;
2105 else if (display->background == NULL /* no way to remove it */)
2107 "background color must be supplied to remove alpha/transparency");
2109 /* Get a copy of the background color (this avoids repeating the checks
2110 * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the
2115 back_g = display->background->green;
2116 if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2118 back_r = display->background->red;
2119 back_b = display->background->blue;
2122 back_b = back_r = back_g;
2126 else if (output_encoding == P_LINEAR)
2127 back_b = back_r = back_g = 65535;
2130 back_b = back_r = back_g = 255;
2132 /* Default the input file gamma if required - this is necessary because
2133 * libpng assumes that if no gamma information is present the data is in the
2134 * output format, but the simplified API deduces the gamma from the input
2137 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2139 /* Do this directly, not using the png_colorspace functions, to ensure
2140 * that it happens even if the colorspace is invalid (though probably if
2141 * it is the setting will be ignored) Note that the same thing can be
2142 * achieved at the application interface with png_set_gAMA.
2144 if (png_ptr->bit_depth == 16 &&
2145 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2146 png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2149 png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2151 png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2154 /* Decide what to do based on the PNG color type of the input data. The
2155 * utility function png_create_colormap_entry deals with most aspects of the
2156 * output transformations; this code works out how to produce bytes of
2157 * color-map entries from the original format.
2159 switch (png_ptr->color_type)
2161 case PNG_COLOR_TYPE_GRAY:
2162 if (png_ptr->bit_depth <= 8)
2164 /* There at most 256 colors in the output, regardless of
2167 unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2169 cmap_entries = 1U << png_ptr->bit_depth;
2170 if (cmap_entries > image->colormap_entries)
2171 png_error(png_ptr, "gray[8] color-map: too few entries");
2173 step = 255 / (cmap_entries - 1);
2174 output_processing = PNG_CMAP_NONE;
2176 /* If there is a tRNS chunk then this either selects a transparent
2177 * value or, if the output has no alpha, the background color.
2179 if (png_ptr->num_trans > 0)
2181 trans = png_ptr->trans_color.gray;
2183 if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2184 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2187 /* png_create_colormap_entry just takes an RGBA and writes the
2188 * corresponding color-map entry using the format from 'image',
2189 * including the required conversion to sRGB or linear as
2190 * appropriate. The input values are always either sRGB (if the
2191 * gamma correction flag is 0) or 0..255 scaled file encoded values
2192 * (if the function must gamma correct them).
2194 for (i=val=0; i<cmap_entries; ++i, val += step)
2196 /* 'i' is a file value. While this will result in duplicated
2197 * entries for 8-bit non-sRGB encoded files it is necessary to
2198 * have non-gamma corrected values to do tRNS handling.
2201 png_create_colormap_entry(display, i, val, val, val, 255,
2202 P_FILE/*8-bit with file gamma*/);
2204 /* Else this entry is transparent. The colors don't matter if
2205 * there is an alpha channel (back_alpha == 0), but it does no
2206 * harm to pass them in; the values are not set above so this
2209 * NOTE: this preserves the full precision of the application
2210 * supplied background color when it is used.
2213 png_create_colormap_entry(display, i, back_r, back_g, back_b,
2214 back_alpha, output_encoding);
2217 /* We need libpng to preserve the original encoding. */
2218 data_encoding = P_FILE;
2220 /* The rows from libpng, while technically gray values, are now also
2221 * color-map indices; however, they may need to be expanded to 1
2222 * byte per pixel. This is what png_set_packing does (i.e., it
2223 * unpacks the bit values into bytes.)
2225 if (png_ptr->bit_depth < 8)
2226 png_set_packing(png_ptr);
2229 else /* bit depth is 16 */
2231 /* The 16-bit input values can be converted directly to 8-bit gamma
2232 * encoded values; however, if a tRNS chunk is present 257 color-map
2233 * entries are required. This means that the extra entry requires
2234 * special processing; add an alpha channel, sacrifice gray level
2235 * 254 and convert transparent (alpha==0) entries to that.
2237 * Use libpng to chop the data to 8 bits. Convert it to sRGB at the
2238 * same time to minimize quality loss. If a tRNS chunk is present
2239 * this means libpng must handle it too; otherwise it is impossible
2240 * to do the exact match on the 16-bit value.
2242 * If the output has no alpha channel *and* the background color is
2243 * gray then it is possible to let libpng handle the substitution by
2244 * ensuring that the corresponding gray level matches the background
2247 data_encoding = P_sRGB;
2249 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2250 png_error(png_ptr, "gray[16] color-map: too few entries");
2252 cmap_entries = make_gray_colormap(display);
2254 if (png_ptr->num_trans > 0)
2256 unsigned int back_alpha;
2258 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2263 if (back_r == back_g && back_g == back_b)
2265 /* Background is gray; no special processing will be
2269 png_uint_32 gray = back_g;
2271 if (output_encoding == P_LINEAR)
2273 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2275 /* And make sure the corresponding palette entry
2278 png_create_colormap_entry(display, gray, back_g, back_g,
2279 back_g, 65535, P_LINEAR);
2282 /* The background passed to libpng, however, must be the
2285 c.index = 0; /*unused*/
2286 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2288 /* NOTE: does this work without expanding tRNS to alpha?
2289 * It should be the color->gray case below apparently
2292 png_set_background_fixed(png_ptr, &c,
2293 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2294 0/*gamma: not used*/);
2296 output_processing = PNG_CMAP_NONE;
2300 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2305 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2309 /* output_processing means that the libpng-processed row will be
2310 * 8-bit GA and it has to be processing to single byte color-map
2311 * values. Entry 254 is replaced by either a completely
2312 * transparent entry or by the background color at full
2313 * precision (and the background color is not a simple gray
2314 * level in this case.)
2317 output_processing = PNG_CMAP_TRANS;
2318 background_index = 254;
2320 /* And set (overwrite) color-map entry 254 to the actual
2321 * background color at full precision.
2323 png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2324 back_alpha, output_encoding);
2328 output_processing = PNG_CMAP_NONE;
2332 case PNG_COLOR_TYPE_GRAY_ALPHA:
2333 /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum
2334 * of 65536 combinations. If, however, the alpha channel is to be
2335 * removed there are only 256 possibilities if the background is gray.
2336 * (Otherwise there is a subset of the 65536 possibilities defined by
2337 * the triangle between black, white and the background color.)
2339 * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to
2340 * worry about tRNS matching - tRNS is ignored if there is an alpha
2343 data_encoding = P_sRGB;
2345 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2347 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2348 png_error(png_ptr, "gray+alpha color-map: too few entries");
2350 cmap_entries = make_ga_colormap(display);
2352 background_index = PNG_CMAP_GA_BACKGROUND;
2353 output_processing = PNG_CMAP_GA;
2356 else /* alpha is removed */
2358 /* Alpha must be removed as the PNG data is processed when the
2359 * background is a color because the G and A channels are
2360 * independent and the vector addition (non-parallel vectors) is a
2363 * This can be reduced to the same algorithm as above by making a
2364 * colormap containing gray levels (for the opaque grays), a
2365 * background entry (for a transparent pixel) and a set of four six
2366 * level color values, one set for each intermediate alpha value.
2367 * See the comments in make_ga_colormap for how this works in the
2368 * per-pixel processing.
2370 * If the background is gray, however, we only need a 256 entry gray
2371 * level color map. It is sufficient to make the entry generated
2372 * for the background color be exactly the color specified.
2374 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2375 (back_r == back_g && back_g == back_b))
2377 /* Background is gray; no special processing will be required. */
2379 png_uint_32 gray = back_g;
2381 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2382 png_error(png_ptr, "gray-alpha color-map: too few entries");
2384 cmap_entries = make_gray_colormap(display);
2386 if (output_encoding == P_LINEAR)
2388 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2390 /* And make sure the corresponding palette entry matches. */
2391 png_create_colormap_entry(display, gray, back_g, back_g,
2392 back_g, 65535, P_LINEAR);
2395 /* The background passed to libpng, however, must be the sRGB
2398 c.index = 0; /*unused*/
2399 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2401 png_set_background_fixed(png_ptr, &c,
2402 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2403 0/*gamma: not used*/);
2405 output_processing = PNG_CMAP_NONE;
2412 /* This is the same as png_make_ga_colormap, above, except that
2413 * the entries are all opaque.
2415 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2416 png_error(png_ptr, "ga-alpha color-map: too few entries");
2421 png_uint_32 gray = (i * 256 + 115) / 231;
2422 png_create_colormap_entry(display, i++, gray, gray, gray,
2426 /* NOTE: this preserves the full precision of the application
2429 background_index = i;
2430 png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2432 /* Coverity claims that output_encoding
2433 * cannot be 2 (P_LINEAR) here.
2436 output_encoding == P_LINEAR ? 65535U : 255U,
2440 /* For non-opaque input composite on the sRGB background - this
2441 * requires inverting the encoding for each component. The input
2442 * is still converted to the sRGB encoding because this is a
2443 * reasonable approximate to the logarithmic curve of human
2444 * visual sensitivity, at least over the narrow range which PNG
2445 * represents. Consequently 'G' is always sRGB encoded, while
2446 * 'A' is linear. We need the linear background colors.
2448 if (output_encoding == P_sRGB) /* else already linear */
2450 /* This may produce a value not exactly matching the
2451 * background, but that's ok because these numbers are only
2452 * used when alpha != 0
2454 back_r = png_sRGB_table[back_r];
2455 back_g = png_sRGB_table[back_g];
2456 back_b = png_sRGB_table[back_b];
2463 /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2464 * by an 8-bit alpha value (0..255).
2466 png_uint_32 alpha = 51 * a;
2467 png_uint_32 back_rx = (255-alpha) * back_r;
2468 png_uint_32 back_gx = (255-alpha) * back_g;
2469 png_uint_32 back_bx = (255-alpha) * back_b;
2473 png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2475 png_create_colormap_entry(display, i++,
2476 PNG_sRGB_FROM_LINEAR(gray + back_rx),
2477 PNG_sRGB_FROM_LINEAR(gray + back_gx),
2478 PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2483 output_processing = PNG_CMAP_GA;
2488 case PNG_COLOR_TYPE_RGB:
2489 case PNG_COLOR_TYPE_RGB_ALPHA:
2490 /* Exclude the case where the output is gray; we can always handle this
2491 * with the cases above.
2493 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2495 /* The color-map will be grayscale, so we may as well convert the
2496 * input RGB values to a simple grayscale and use the grayscale
2499 * NOTE: calling this apparently damages the recognition of the
2500 * transparent color in background color handling; call
2501 * png_set_tRNS_to_alpha before png_set_background_fixed.
2503 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2505 data_encoding = P_sRGB;
2507 /* The output will now be one or two 8-bit gray or gray+alpha
2508 * channels. The more complex case arises when the input has alpha.
2510 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2511 png_ptr->num_trans > 0) &&
2512 (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2514 /* Both input and output have an alpha channel, so no background
2515 * processing is required; just map the GA bytes to the right
2520 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2521 png_error(png_ptr, "rgb[ga] color-map: too few entries");
2523 cmap_entries = make_ga_colormap(display);
2524 background_index = PNG_CMAP_GA_BACKGROUND;
2525 output_processing = PNG_CMAP_GA;
2530 /* Either the input or the output has no alpha channel, so there
2531 * will be no non-opaque pixels in the color-map; it will just be
2534 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2535 png_error(png_ptr, "rgb[gray] color-map: too few entries");
2537 /* Ideally this code would use libpng to do the gamma correction,
2538 * but if an input alpha channel is to be removed we will hit the
2539 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2540 * correction bug). Fix this by dropping the gamma correction in
2541 * this case and doing it in the palette; this will result in
2542 * duplicate palette entries, but that's better than the
2543 * alternative of double gamma correction.
2545 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2546 png_ptr->num_trans > 0) &&
2547 png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2549 cmap_entries = make_gray_file_colormap(display);
2550 data_encoding = P_FILE;
2554 cmap_entries = make_gray_colormap(display);
2556 /* But if the input has alpha or transparency it must be removed
2558 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2559 png_ptr->num_trans > 0)
2562 png_uint_32 gray = back_g;
2564 /* We need to ensure that the application background exists in
2565 * the colormap and that completely transparent pixels map to
2566 * it. Achieve this simply by ensuring that the entry
2567 * selected for the background really is the background color.
2569 if (data_encoding == P_FILE) /* from the fixup above */
2571 /* The app supplied a gray which is in output_encoding, we
2572 * need to convert it to a value of the input (P_FILE)
2573 * encoding then set this palette entry to the required
2576 if (output_encoding == P_sRGB)
2577 gray = png_sRGB_table[gray]; /* now P_LINEAR */
2579 gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2580 png_ptr->colorspace.gamma)); /* now P_FILE */
2582 /* And make sure the corresponding palette entry contains
2583 * exactly the required sRGB value.
2585 png_create_colormap_entry(display, gray, back_g, back_g,
2586 back_g, 0/*unused*/, output_encoding);
2589 else if (output_encoding == P_LINEAR)
2591 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2593 /* And make sure the corresponding palette entry matches.
2595 png_create_colormap_entry(display, gray, back_g, back_g,
2596 back_g, 0/*unused*/, P_LINEAR);
2599 /* The background passed to libpng, however, must be the
2600 * output (normally sRGB) value.
2602 c.index = 0; /*unused*/
2603 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2605 /* NOTE: the following is apparently a bug in libpng. Without
2606 * it the transparent color recognition in
2607 * png_set_background_fixed seems to go wrong.
2610 png_set_background_fixed(png_ptr, &c,
2611 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2612 0/*gamma: not used*/);
2615 output_processing = PNG_CMAP_NONE;
2619 else /* output is color */
2621 /* We could use png_quantize here so long as there is no transparent
2622 * color or alpha; png_quantize ignores alpha. Easier overall just
2623 * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2624 * Consequently we always want libpng to produce sRGB data.
2626 data_encoding = P_sRGB;
2628 /* Is there any transparency or alpha? */
2629 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2630 png_ptr->num_trans > 0)
2632 /* Is there alpha in the output too? If so all four channels are
2633 * processed into a special RGB cube with alpha support.
2635 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2639 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2640 png_error(png_ptr, "rgb+alpha color-map: too few entries");
2642 cmap_entries = make_rgb_colormap(display);
2644 /* Add a transparent entry. */
2645 png_create_colormap_entry(display, cmap_entries, 255, 255,
2648 /* This is stored as the background index for the processing
2651 background_index = cmap_entries++;
2653 /* Add 27 r,g,b entries each with alpha 0.5. */
2654 for (r=0; r<256; r = (r << 1) | 0x7f)
2658 for (g=0; g<256; g = (g << 1) | 0x7f)
2662 /* This generates components with the values 0, 127 and
2665 for (b=0; b<256; b = (b << 1) | 0x7f)
2666 png_create_colormap_entry(display, cmap_entries++,
2667 r, g, b, 128, P_sRGB);
2672 output_processing = PNG_CMAP_RGB_ALPHA;
2677 /* Alpha/transparency must be removed. The background must
2678 * exist in the color map (achieved by setting adding it after
2679 * the 666 color-map). If the standard processing code will
2680 * pick up this entry automatically that's all that is
2681 * required; libpng can be called to do the background
2684 unsigned int sample_size =
2685 PNG_IMAGE_SAMPLE_SIZE(output_format);
2686 png_uint_32 r, g, b; /* sRGB background */
2688 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2689 png_error(png_ptr, "rgb-alpha color-map: too few entries");
2691 cmap_entries = make_rgb_colormap(display);
2693 png_create_colormap_entry(display, cmap_entries, back_r,
2694 back_g, back_b, 0/*unused*/, output_encoding);
2696 if (output_encoding == P_LINEAR)
2698 r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2699 g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2700 b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2710 /* Compare the newly-created color-map entry with the one the
2711 * PNG_CMAP_RGB algorithm will use. If the two entries don't
2712 * match, add the new one and set this as the background
2715 if (memcmp((png_const_bytep)display->colormap +
2716 sample_size * cmap_entries,
2717 (png_const_bytep)display->colormap +
2718 sample_size * PNG_RGB_INDEX(r,g,b),
2721 /* The background color must be added. */
2722 background_index = cmap_entries++;
2724 /* Add 27 r,g,b entries each with created by composing with
2725 * the background at alpha 0.5.
2727 for (r=0; r<256; r = (r << 1) | 0x7f)
2729 for (g=0; g<256; g = (g << 1) | 0x7f)
2731 /* This generates components with the values 0, 127
2734 for (b=0; b<256; b = (b << 1) | 0x7f)
2735 png_create_colormap_entry(display, cmap_entries++,
2736 png_colormap_compose(display, r, P_sRGB, 128,
2737 back_r, output_encoding),
2738 png_colormap_compose(display, g, P_sRGB, 128,
2739 back_g, output_encoding),
2740 png_colormap_compose(display, b, P_sRGB, 128,
2741 back_b, output_encoding),
2742 0/*unused*/, output_encoding);
2747 output_processing = PNG_CMAP_RGB_ALPHA;
2750 else /* background color is in the standard color-map */
2754 c.index = 0; /*unused*/
2755 c.red = (png_uint_16)back_r;
2756 c.gray = c.green = (png_uint_16)back_g;
2757 c.blue = (png_uint_16)back_b;
2759 png_set_background_fixed(png_ptr, &c,
2760 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2761 0/*gamma: not used*/);
2763 output_processing = PNG_CMAP_RGB;
2768 else /* no alpha or transparency in the input */
2770 /* Alpha in the output is irrelevant, simply map the opaque input
2771 * pixels to the 6x6x6 color-map.
2773 if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2774 png_error(png_ptr, "rgb color-map: too few entries");
2776 cmap_entries = make_rgb_colormap(display);
2777 output_processing = PNG_CMAP_RGB;
2782 case PNG_COLOR_TYPE_PALETTE:
2783 /* It's already got a color-map. It may be necessary to eliminate the
2784 * tRNS entries though.
2787 unsigned int num_trans = png_ptr->num_trans;
2788 png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2789 png_const_colorp colormap = png_ptr->palette;
2790 const int do_background = trans != NULL &&
2791 (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2798 output_processing = PNG_CMAP_NONE;
2799 data_encoding = P_FILE; /* Don't change from color-map indices */
2800 cmap_entries = png_ptr->num_palette;
2801 if (cmap_entries > 256)
2804 if (cmap_entries > image->colormap_entries)
2805 png_error(png_ptr, "palette color-map: too few entries");
2807 for (i=0; i < cmap_entries; ++i)
2809 if (do_background != 0 && i < num_trans && trans[i] < 255)
2812 png_create_colormap_entry(display, i, back_r, back_g,
2813 back_b, 0, output_encoding);
2817 /* Must compose the PNG file color in the color-map entry
2818 * on the sRGB color in 'back'.
2820 png_create_colormap_entry(display, i,
2821 png_colormap_compose(display, colormap[i].red,
2822 P_FILE, trans[i], back_r, output_encoding),
2823 png_colormap_compose(display, colormap[i].green,
2824 P_FILE, trans[i], back_g, output_encoding),
2825 png_colormap_compose(display, colormap[i].blue,
2826 P_FILE, trans[i], back_b, output_encoding),
2827 output_encoding == P_LINEAR ? trans[i] * 257U :
2834 png_create_colormap_entry(display, i, colormap[i].red,
2835 colormap[i].green, colormap[i].blue,
2836 i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2839 /* The PNG data may have indices packed in fewer than 8 bits, it
2840 * must be expanded if so.
2842 if (png_ptr->bit_depth < 8)
2843 png_set_packing(png_ptr);
2848 png_error(png_ptr, "invalid PNG color type");
2852 /* Now deal with the output processing */
2853 if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2854 (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2855 png_set_tRNS_to_alpha(png_ptr);
2857 switch (data_encoding)
2860 /* Change to 8-bit sRGB */
2861 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
2865 if (png_ptr->bit_depth > 8)
2866 png_set_scale_16(png_ptr);
2871 png_error(png_ptr, "bad data option (internal error)");
2875 if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
2876 png_error(png_ptr, "color map overflow (BAD internal error)");
2878 image->colormap_entries = cmap_entries;
2880 /* Double check using the recorded background index */
2881 switch (output_processing)
2884 if (background_index != PNG_CMAP_NONE_BACKGROUND)
2885 goto bad_background;
2889 if (background_index != PNG_CMAP_GA_BACKGROUND)
2890 goto bad_background;
2893 case PNG_CMAP_TRANS:
2894 if (background_index >= cmap_entries ||
2895 background_index != PNG_CMAP_TRANS_BACKGROUND)
2896 goto bad_background;
2900 if (background_index != PNG_CMAP_RGB_BACKGROUND)
2901 goto bad_background;
2904 case PNG_CMAP_RGB_ALPHA:
2905 if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
2906 goto bad_background;
2910 png_error(png_ptr, "bad processing option (internal error)");
2913 png_error(png_ptr, "bad background index (internal error)");
2916 display->colormap_processing = output_processing;
2921 /* The final part of the color-map read called from png_image_finish_read. */
2923 png_image_read_and_map(png_voidp argument)
2925 png_image_read_control *display = png_voidcast(png_image_read_control*,
2927 png_imagep image = display->image;
2928 png_structrp png_ptr = image->opaque->png_ptr;
2931 /* Called when the libpng data must be transformed into the color-mapped
2932 * form. There is a local row buffer in display->local and this routine must
2933 * do the interlace handling.
2935 switch (png_ptr->interlaced)
2937 case PNG_INTERLACE_NONE:
2941 case PNG_INTERLACE_ADAM7:
2942 passes = PNG_INTERLACE_ADAM7_PASSES;
2946 png_error(png_ptr, "unknown interlace type");
2950 png_uint_32 height = image->height;
2951 png_uint_32 width = image->width;
2952 int proc = display->colormap_processing;
2953 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
2954 ptrdiff_t step_row = display->row_bytes;
2957 for (pass = 0; pass < passes; ++pass)
2959 unsigned int startx, stepx, stepy;
2962 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
2964 /* The row may be empty for a short image: */
2965 if (PNG_PASS_COLS(width, pass) == 0)
2968 startx = PNG_PASS_START_COL(pass);
2969 stepx = PNG_PASS_COL_OFFSET(pass);
2970 y = PNG_PASS_START_ROW(pass);
2971 stepy = PNG_PASS_ROW_OFFSET(pass);
2981 for (; y<height; y += stepy)
2983 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
2984 png_bytep outrow = first_row + y * step_row;
2985 png_const_bytep end_row = outrow + width;
2987 /* Read read the libpng data into the temporary buffer. */
2988 png_read_row(png_ptr, inrow, NULL);
2990 /* Now process the row according to the processing option, note
2991 * that the caller verifies that the format of the libpng output
2992 * data is as required.
2998 for (; outrow < end_row; outrow += stepx)
3000 /* The data is always in the PNG order */
3001 unsigned int gray = *inrow++;
3002 unsigned int alpha = *inrow++;
3005 /* NOTE: this code is copied as a comment in
3006 * make_ga_colormap above. Please update the
3007 * comment if you change this code!
3009 if (alpha > 229) /* opaque */
3011 entry = (231 * gray + 128) >> 8;
3013 else if (alpha < 26) /* transparent */
3017 else /* partially opaque */
3019 entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3022 *outrow = (png_byte)entry;
3026 case PNG_CMAP_TRANS:
3027 for (; outrow < end_row; outrow += stepx)
3029 png_byte gray = *inrow++;
3030 png_byte alpha = *inrow++;
3033 *outrow = PNG_CMAP_TRANS_BACKGROUND;
3035 else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3039 *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3044 for (; outrow < end_row; outrow += stepx)
3046 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3051 case PNG_CMAP_RGB_ALPHA:
3052 for (; outrow < end_row; outrow += stepx)
3054 unsigned int alpha = inrow[3];
3056 /* Because the alpha entries only hold alpha==0.5 values
3057 * split the processing at alpha==0.25 (64) and 0.75
3062 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3065 else if (alpha < 64)
3066 *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3070 /* Likewise there are three entries for each of r, g
3071 * and b. We could select the entry by popcount on
3072 * the top two bits on those architectures that
3073 * support it, this is what the code below does,
3076 unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3078 /* Here are how the values map:
3084 * So, as above with the explicit alpha checks, the
3085 * breakpoints are at 64 and 196.
3087 if (inrow[0] & 0x80) back_i += 9; /* red */
3088 if (inrow[0] & 0x40) back_i += 9;
3089 if (inrow[0] & 0x80) back_i += 3; /* green */
3090 if (inrow[0] & 0x40) back_i += 3;
3091 if (inrow[0] & 0x80) back_i += 1; /* blue */
3092 if (inrow[0] & 0x40) back_i += 1;
3094 *outrow = (png_byte)back_i;
3112 png_image_read_colormapped(png_voidp argument)
3114 png_image_read_control *display = png_voidcast(png_image_read_control*,
3116 png_imagep image = display->image;
3117 png_controlp control = image->opaque;
3118 png_structrp png_ptr = control->png_ptr;
3119 png_inforp info_ptr = control->info_ptr;
3121 int passes = 0; /* As a flag */
3123 PNG_SKIP_CHUNKS(png_ptr);
3125 /* Update the 'info' structure and make sure the result is as required; first
3126 * make sure to turn on the interlace handling if it will be required
3127 * (because it can't be turned on *after* the call to png_read_update_info!)
3129 if (display->colormap_processing == PNG_CMAP_NONE)
3130 passes = png_set_interlace_handling(png_ptr);
3132 png_read_update_info(png_ptr, info_ptr);
3134 /* The expected output can be deduced from the colormap_processing option. */
3135 switch (display->colormap_processing)
3138 /* Output must be one channel and one byte per pixel, the output
3139 * encoding can be anything.
3141 if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3142 info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3143 info_ptr->bit_depth == 8)
3148 case PNG_CMAP_TRANS:
3150 /* Output must be two channels and the 'G' one must be sRGB, the latter
3151 * can be checked with an exact number because it should have been set
3152 * to this number above!
3154 if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3155 info_ptr->bit_depth == 8 &&
3156 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3157 image->colormap_entries == 256)
3163 /* Output must be 8-bit sRGB encoded RGB */
3164 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3165 info_ptr->bit_depth == 8 &&
3166 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3167 image->colormap_entries == 216)
3172 case PNG_CMAP_RGB_ALPHA:
3173 /* Output must be 8-bit sRGB encoded RGBA */
3174 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3175 info_ptr->bit_depth == 8 &&
3176 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3177 image->colormap_entries == 244 /* 216 + 1 + 27 */)
3180 /* goto bad_output; */
3185 png_error(png_ptr, "bad color-map processing (internal error)");
3188 /* Now read the rows. Do this here if it is possible to read directly into
3189 * the output buffer, otherwise allocate a local row buffer of the maximum
3190 * size libpng requires and call the relevant processing routine safely.
3193 png_voidp first_row = display->buffer;
3194 ptrdiff_t row_bytes = display->row_stride;
3196 /* The following expression is designed to work correctly whether it gives
3197 * a signed or an unsigned result.
3201 char *ptr = png_voidcast(char*, first_row);
3202 ptr += (image->height-1) * (-row_bytes);
3203 first_row = png_voidcast(png_voidp, ptr);
3206 display->first_row = first_row;
3207 display->row_bytes = row_bytes;
3213 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3215 display->local_row = row;
3216 result = png_safe_execute(image, png_image_read_and_map, display);
3217 display->local_row = NULL;
3218 png_free(png_ptr, row);
3225 png_alloc_size_t row_bytes = display->row_bytes;
3227 while (--passes >= 0)
3229 png_uint_32 y = image->height;
3230 png_bytep row = png_voidcast(png_bytep, display->first_row);
3234 png_read_row(png_ptr, row, NULL);
3243 /* Just the row reading part of png_image_read. */
3245 png_image_read_composite(png_voidp argument)
3247 png_image_read_control *display = png_voidcast(png_image_read_control*,
3249 png_imagep image = display->image;
3250 png_structrp png_ptr = image->opaque->png_ptr;
3253 switch (png_ptr->interlaced)
3255 case PNG_INTERLACE_NONE:
3259 case PNG_INTERLACE_ADAM7:
3260 passes = PNG_INTERLACE_ADAM7_PASSES;
3264 png_error(png_ptr, "unknown interlace type");
3268 png_uint_32 height = image->height;
3269 png_uint_32 width = image->width;
3270 ptrdiff_t step_row = display->row_bytes;
3271 unsigned int channels =
3272 (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3275 for (pass = 0; pass < passes; ++pass)
3277 unsigned int startx, stepx, stepy;
3280 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3282 /* The row may be empty for a short image: */
3283 if (PNG_PASS_COLS(width, pass) == 0)
3286 startx = PNG_PASS_START_COL(pass) * channels;
3287 stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3288 y = PNG_PASS_START_ROW(pass);
3289 stepy = PNG_PASS_ROW_OFFSET(pass);
3300 for (; y<height; y += stepy)
3302 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3304 png_const_bytep end_row;
3306 /* Read the row, which is packed: */
3307 png_read_row(png_ptr, inrow, NULL);
3309 outrow = png_voidcast(png_bytep, display->first_row);
3310 outrow += y * step_row;
3311 end_row = outrow + width * channels;
3313 /* Now do the composition on each pixel in this row. */
3315 for (; outrow < end_row; outrow += stepx)
3317 png_byte alpha = inrow[channels];
3319 if (alpha > 0) /* else no change to the output */
3323 for (c=0; c<channels; ++c)
3325 png_uint_32 component = inrow[c];
3327 if (alpha < 255) /* else just use component */
3329 /* This is PNG_OPTIMIZED_ALPHA, the component value
3330 * is a linear 8-bit value. Combine this with the
3331 * current outrow[c] value which is sRGB encoded.
3332 * Arithmetic here is 16-bits to preserve the output
3335 component *= 257*255; /* =65535 */
3336 component += (255-alpha)*png_sRGB_table[outrow[c]];
3338 /* So 'component' is scaled by 255*65535 and is
3339 * therefore appropriate for the sRGB to linear
3342 component = PNG_sRGB_FROM_LINEAR(component);
3345 outrow[c] = (png_byte)component;
3349 inrow += channels+1; /* components and alpha channel */
3358 /* The do_local_background case; called when all the following transforms are to
3365 * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3366 * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3367 * correction. The fix-up is to prevent the PNG_COMPOSITE operation from
3368 * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3369 * row and handles the removal or pre-multiplication of the alpha channel.
3372 png_image_read_background(png_voidp argument)
3374 png_image_read_control *display = png_voidcast(png_image_read_control*,
3376 png_imagep image = display->image;
3377 png_structrp png_ptr = image->opaque->png_ptr;
3378 png_inforp info_ptr = image->opaque->info_ptr;
3379 png_uint_32 height = image->height;
3380 png_uint_32 width = image->width;
3383 /* Double check the convoluted logic below. We expect to get here with
3384 * libpng doing rgb to gray and gamma correction but background processing
3385 * left to the png_image_read_background function. The rows libpng produce
3386 * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3388 if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3389 png_error(png_ptr, "lost rgb to gray");
3391 if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3392 png_error(png_ptr, "unexpected compose");
3394 if (png_get_channels(png_ptr, info_ptr) != 2)
3395 png_error(png_ptr, "lost/gained channels");
3397 /* Expect the 8-bit case to always remove the alpha channel */
3398 if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3399 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3400 png_error(png_ptr, "unexpected 8-bit transformation");
3402 switch (png_ptr->interlaced)
3404 case PNG_INTERLACE_NONE:
3408 case PNG_INTERLACE_ADAM7:
3409 passes = PNG_INTERLACE_ADAM7_PASSES;
3413 png_error(png_ptr, "unknown interlace type");
3416 /* Use direct access to info_ptr here because otherwise the simplified API
3417 * would require PNG_EASY_ACCESS_SUPPORTED (just for this.) Note this is
3418 * checking the value after libpng expansions, not the original value in the
3421 switch (info_ptr->bit_depth)
3424 /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3425 * to be removed by composing on a background: either the row if
3426 * display->background is NULL or display->background->green if not.
3427 * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3430 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3431 ptrdiff_t step_row = display->row_bytes;
3433 for (pass = 0; pass < passes; ++pass)
3435 png_bytep row = png_voidcast(png_bytep, display->first_row);
3436 unsigned int startx, stepx, stepy;
3439 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3441 /* The row may be empty for a short image: */
3442 if (PNG_PASS_COLS(width, pass) == 0)
3445 startx = PNG_PASS_START_COL(pass);
3446 stepx = PNG_PASS_COL_OFFSET(pass);
3447 y = PNG_PASS_START_ROW(pass);
3448 stepy = PNG_PASS_ROW_OFFSET(pass);
3458 if (display->background == NULL)
3460 for (; y<height; y += stepy)
3462 png_bytep inrow = png_voidcast(png_bytep,
3463 display->local_row);
3464 png_bytep outrow = first_row + y * step_row;
3465 png_const_bytep end_row = outrow + width;
3467 /* Read the row, which is packed: */
3468 png_read_row(png_ptr, inrow, NULL);
3470 /* Now do the composition on each pixel in this row. */
3472 for (; outrow < end_row; outrow += stepx)
3474 png_byte alpha = inrow[1];
3476 if (alpha > 0) /* else no change to the output */
3478 png_uint_32 component = inrow[0];
3480 if (alpha < 255) /* else just use component */
3482 /* Since PNG_OPTIMIZED_ALPHA was not set it is
3483 * necessary to invert the sRGB transfer
3484 * function and multiply the alpha out.
3486 component = png_sRGB_table[component] * alpha;
3487 component += png_sRGB_table[outrow[0]] *
3489 component = PNG_sRGB_FROM_LINEAR(component);
3492 outrow[0] = (png_byte)component;
3495 inrow += 2; /* gray and alpha channel */
3500 else /* constant background value */
3502 png_byte background8 = display->background->green;
3503 png_uint_16 background = png_sRGB_table[background8];
3505 for (; y<height; y += stepy)
3507 png_bytep inrow = png_voidcast(png_bytep,
3508 display->local_row);
3509 png_bytep outrow = first_row + y * step_row;
3510 png_const_bytep end_row = outrow + width;
3512 /* Read the row, which is packed: */
3513 png_read_row(png_ptr, inrow, NULL);
3515 /* Now do the composition on each pixel in this row. */
3517 for (; outrow < end_row; outrow += stepx)
3519 png_byte alpha = inrow[1];
3521 if (alpha > 0) /* else use background */
3523 png_uint_32 component = inrow[0];
3525 if (alpha < 255) /* else just use component */
3527 component = png_sRGB_table[component] * alpha;
3528 component += background * (255-alpha);
3529 component = PNG_sRGB_FROM_LINEAR(component);
3532 outrow[0] = (png_byte)component;
3536 outrow[0] = background8;
3538 inrow += 2; /* gray and alpha channel */
3541 row += display->row_bytes;
3549 /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3550 * still be done and, maybe, the alpha channel removed. This code also
3551 * handles the alpha-first option.
3554 png_uint_16p first_row = png_voidcast(png_uint_16p,
3555 display->first_row);
3556 /* The division by two is safe because the caller passed in a
3557 * stride which was multiplied by 2 (below) to get row_bytes.
3559 ptrdiff_t step_row = display->row_bytes / 2;
3560 int preserve_alpha = (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
3561 unsigned int outchannels = 1+preserve_alpha;
3564 # ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3565 if (preserve_alpha != 0 &&
3566 (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3570 for (pass = 0; pass < passes; ++pass)
3572 unsigned int startx, stepx, stepy;
3575 /* The 'x' start and step are adjusted to output components here.
3577 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3579 /* The row may be empty for a short image: */
3580 if (PNG_PASS_COLS(width, pass) == 0)
3583 startx = PNG_PASS_START_COL(pass) * outchannels;
3584 stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3585 y = PNG_PASS_START_ROW(pass);
3586 stepy = PNG_PASS_ROW_OFFSET(pass);
3593 stepx = outchannels;
3597 for (; y<height; y += stepy)
3599 png_const_uint_16p inrow;
3600 png_uint_16p outrow = first_row + y*step_row;
3601 png_uint_16p end_row = outrow + width * outchannels;
3603 /* Read the row, which is packed: */
3604 png_read_row(png_ptr, png_voidcast(png_bytep,
3605 display->local_row), NULL);
3606 inrow = png_voidcast(png_const_uint_16p, display->local_row);
3608 /* Now do the pre-multiplication on each pixel in this row.
3611 for (; outrow < end_row; outrow += stepx)
3613 png_uint_32 component = inrow[0];
3614 png_uint_16 alpha = inrow[1];
3616 if (alpha > 0) /* else 0 */
3618 if (alpha < 65535) /* else just use component */
3629 outrow[swap_alpha] = (png_uint_16)component;
3630 if (preserve_alpha != 0)
3631 outrow[1 ^ swap_alpha] = alpha;
3633 inrow += 2; /* components and alpha channel */
3642 png_error(png_ptr, "unexpected bit depth");
3649 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3651 png_image_read_direct(png_voidp argument)
3653 png_image_read_control *display = png_voidcast(png_image_read_control*,
3655 png_imagep image = display->image;
3656 png_structrp png_ptr = image->opaque->png_ptr;
3657 png_inforp info_ptr = image->opaque->info_ptr;
3659 png_uint_32 format = image->format;
3660 int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3661 int do_local_compose = 0;
3662 int do_local_background = 0; /* to avoid double gamma correction bug */
3665 /* Add transforms to ensure the correct output format is produced then check
3666 * that the required implementation support is there. Always expand; always
3667 * need 8 bits minimum, no palette and expanded tRNS.
3669 png_set_expand(png_ptr);
3671 /* Now check the format to see if it was modified. */
3673 png_uint_32 base_format = png_image_format(png_ptr) &
3674 ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3675 png_uint_32 change = format ^ base_format;
3676 png_fixed_point output_gamma;
3677 int mode; /* alpha mode */
3679 /* Do this first so that we have a record if rgb to gray is happening. */
3680 if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3682 /* gray<->color transformation required. */
3683 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3684 png_set_gray_to_rgb(png_ptr);
3688 /* libpng can't do both rgb to gray and
3689 * background/pre-multiplication if there is also significant gamma
3690 * correction, because both operations require linear colors and
3691 * the code only supports one transform doing the gamma correction.
3692 * Handle this by doing the pre-multiplication or background
3693 * operation in this code, if necessary.
3695 * TODO: fix this by rewriting pngrtran.c (!)
3697 * For the moment (given that fixing this in pngrtran.c is an
3698 * enormous change) 'do_local_background' is used to indicate that
3699 * the problem exists.
3701 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3702 do_local_background = 1/*maybe*/;
3704 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3705 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3708 change &= ~PNG_FORMAT_FLAG_COLOR;
3711 /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3714 png_fixed_point input_gamma_default;
3716 if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3717 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3718 input_gamma_default = PNG_GAMMA_LINEAR;
3720 input_gamma_default = PNG_DEFAULT_sRGB;
3722 /* Call png_set_alpha_mode to set the default for the input gamma; the
3723 * output gamma is set by a second call below.
3725 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3730 /* If there *is* an alpha channel in the input it must be multiplied
3731 * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3733 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3734 mode = PNG_ALPHA_STANDARD; /* associated alpha */
3737 mode = PNG_ALPHA_PNG;
3739 output_gamma = PNG_GAMMA_LINEAR;
3744 mode = PNG_ALPHA_PNG;
3745 output_gamma = PNG_DEFAULT_sRGB;
3748 /* If 'do_local_background' is set check for the presence of gamma
3749 * correction; this is part of the work-round for the libpng bug
3752 * TODO: fix libpng and remove this.
3754 if (do_local_background != 0)
3756 png_fixed_point gtest;
3758 /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3759 * gamma correction, the screen gamma hasn't been set on png_struct
3760 * yet; it's set below. png_struct::gamma, however, is set to the
3763 if (png_muldiv(>est, output_gamma, png_ptr->colorspace.gamma,
3764 PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
3765 do_local_background = 0;
3767 else if (mode == PNG_ALPHA_STANDARD)
3769 do_local_background = 2/*required*/;
3770 mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3773 /* else leave as 1 for the checks below */
3776 /* If the bit-depth changes then handle that here. */
3777 if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3779 if (linear != 0 /*16-bit output*/)
3780 png_set_expand_16(png_ptr);
3782 else /* 8-bit output */
3783 png_set_scale_16(png_ptr);
3785 change &= ~PNG_FORMAT_FLAG_LINEAR;
3788 /* Now the background/alpha channel changes. */
3789 if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3791 /* Removing an alpha channel requires composition for the 8-bit
3792 * formats; for the 16-bit it is already done, above, by the
3793 * pre-multiplication and the channel just needs to be stripped.
3795 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3797 /* If RGB->gray is happening the alpha channel must be left and the
3798 * operation completed locally.
3800 * TODO: fix libpng and remove this.
3802 if (do_local_background != 0)
3803 do_local_background = 2/*required*/;
3805 /* 16-bit output: just remove the channel */
3806 else if (linear != 0) /* compose on black (well, pre-multiply) */
3807 png_set_strip_alpha(png_ptr);
3809 /* 8-bit output: do an appropriate compose */
3810 else if (display->background != NULL)
3814 c.index = 0; /*unused*/
3815 c.red = display->background->red;
3816 c.green = display->background->green;
3817 c.blue = display->background->blue;
3818 c.gray = display->background->green;
3820 /* This is always an 8-bit sRGB value, using the 'green' channel
3821 * for gray is much better than calculating the luminance here;
3822 * we can get off-by-one errors in that calculation relative to
3823 * the app expectations and that will show up in transparent
3826 png_set_background_fixed(png_ptr, &c,
3827 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3828 0/*gamma: not used*/);
3831 else /* compose on row: implemented below. */
3833 do_local_compose = 1;
3834 /* This leaves the alpha channel in the output, so it has to be
3835 * removed by the code below. Set the encoding to the 'OPTIMIZE'
3836 * one so the code only has to hack on the pixels that require
3839 mode = PNG_ALPHA_OPTIMIZED;
3843 else /* output needs an alpha channel */
3845 /* This is tricky because it happens before the swap operation has
3846 * been accomplished; however, the swap does *not* swap the added
3847 * alpha channel (weird API), so it must be added in the correct
3850 png_uint_32 filler; /* opaque filler */
3859 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
3860 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3862 where = PNG_FILLER_BEFORE;
3863 change &= ~PNG_FORMAT_FLAG_AFIRST;
3868 where = PNG_FILLER_AFTER;
3870 png_set_add_alpha(png_ptr, filler, where);
3873 /* This stops the (irrelevant) call to swap_alpha below. */
3874 change &= ~PNG_FORMAT_FLAG_ALPHA;
3877 /* Now set the alpha mode correctly; this is always done, even if there is
3878 * no alpha channel in either the input or the output because it correctly
3879 * sets the output gamma.
3881 png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
3883 # ifdef PNG_FORMAT_BGR_SUPPORTED
3884 if ((change & PNG_FORMAT_FLAG_BGR) != 0)
3886 /* Check only the output format; PNG is never BGR; don't do this if
3887 * the output is gray, but fix up the 'format' value in that case.
3889 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3890 png_set_bgr(png_ptr);
3893 format &= ~PNG_FORMAT_FLAG_BGR;
3895 change &= ~PNG_FORMAT_FLAG_BGR;
3899 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
3900 if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
3902 /* Only relevant if there is an alpha channel - it's particularly
3903 * important to handle this correctly because do_local_compose may
3904 * be set above and then libpng will keep the alpha channel for this
3907 if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
3909 /* Disable this if doing a local background,
3910 * TODO: remove this when local background is no longer required.
3912 if (do_local_background != 2)
3913 png_set_swap_alpha(png_ptr);
3917 format &= ~PNG_FORMAT_FLAG_AFIRST;
3919 change &= ~PNG_FORMAT_FLAG_AFIRST;
3923 /* If the *output* is 16-bit then we need to check for a byte-swap on this
3928 PNG_CONST png_uint_16 le = 0x0001;
3930 if ((*(png_const_bytep) & le) != 0)
3931 png_set_swap(png_ptr);
3934 /* If change is not now 0 some transformation is missing - error out. */
3936 png_error(png_ptr, "png_read_image: unsupported transformation");
3939 PNG_SKIP_CHUNKS(png_ptr);
3941 /* Update the 'info' structure and make sure the result is as required; first
3942 * make sure to turn on the interlace handling if it will be required
3943 * (because it can't be turned on *after* the call to png_read_update_info!)
3945 * TODO: remove the do_local_background fixup below.
3947 if (do_local_compose == 0 && do_local_background != 2)
3948 passes = png_set_interlace_handling(png_ptr);
3950 png_read_update_info(png_ptr, info_ptr);
3953 png_uint_32 info_format = 0;
3955 if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
3956 info_format |= PNG_FORMAT_FLAG_COLOR;
3958 if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
3960 /* do_local_compose removes this channel below. */
3961 if (do_local_compose == 0)
3963 /* do_local_background does the same if required. */
3964 if (do_local_background != 2 ||
3965 (format & PNG_FORMAT_FLAG_ALPHA) != 0)
3966 info_format |= PNG_FORMAT_FLAG_ALPHA;
3970 else if (do_local_compose != 0) /* internal error */
3971 png_error(png_ptr, "png_image_read: alpha channel lost");
3973 if (info_ptr->bit_depth == 16)
3974 info_format |= PNG_FORMAT_FLAG_LINEAR;
3976 #ifdef PNG_FORMAT_BGR_SUPPORTED
3977 if ((png_ptr->transformations & PNG_BGR) != 0)
3978 info_format |= PNG_FORMAT_FLAG_BGR;
3981 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
3982 if (do_local_background == 2)
3984 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
3985 info_format |= PNG_FORMAT_FLAG_AFIRST;
3988 if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
3989 ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
3990 (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
3992 if (do_local_background == 2)
3993 png_error(png_ptr, "unexpected alpha swap transformation");
3995 info_format |= PNG_FORMAT_FLAG_AFIRST;
3999 /* This is actually an internal error. */
4000 if (info_format != format)
4001 png_error(png_ptr, "png_read_image: invalid transformations");
4004 /* Now read the rows. If do_local_compose is set then it is necessary to use
4005 * a local row buffer. The output will be GA, RGBA or BGRA and must be
4006 * converted to G, RGB or BGR as appropriate. The 'local_row' member of the
4007 * display acts as a flag.
4010 png_voidp first_row = display->buffer;
4011 ptrdiff_t row_bytes = display->row_stride;
4016 /* The following expression is designed to work correctly whether it gives
4017 * a signed or an unsigned result.
4021 char *ptr = png_voidcast(char*, first_row);
4022 ptr += (image->height-1) * (-row_bytes);
4023 first_row = png_voidcast(png_voidp, ptr);
4026 display->first_row = first_row;
4027 display->row_bytes = row_bytes;
4030 if (do_local_compose != 0)
4033 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4035 display->local_row = row;
4036 result = png_safe_execute(image, png_image_read_composite, display);
4037 display->local_row = NULL;
4038 png_free(png_ptr, row);
4043 else if (do_local_background == 2)
4046 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4048 display->local_row = row;
4049 result = png_safe_execute(image, png_image_read_background, display);
4050 display->local_row = NULL;
4051 png_free(png_ptr, row);
4058 png_alloc_size_t row_bytes = display->row_bytes;
4060 while (--passes >= 0)
4062 png_uint_32 y = image->height;
4063 png_bytep row = png_voidcast(png_bytep, display->first_row);
4067 png_read_row(png_ptr, row, NULL);
4077 png_image_finish_read(png_imagep image, png_const_colorp background,
4078 void *buffer, png_int_32 row_stride, void *colormap)
4080 if (image != NULL && image->version == PNG_IMAGE_VERSION)
4082 /* Check for row_stride overflow. This check is not performed on the
4083 * original PNG format because it may not occur in the output PNG format
4084 * and libpng deals with the issues of reading the original.
4086 const unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4088 /* The following checks just the 'row_stride' calculation to ensure it
4089 * fits in a signed 32-bit value. Because channels/components can be
4090 * either 1 or 2 bytes in size the length of a row can still overflow 32
4091 * bits; this is just to verify that the 'row_stride' argument can be
4094 if (image->width <= 0x7FFFFFFFU/channels) /* no overflow */
4097 const png_uint_32 png_row_stride = image->width * channels;
4099 if (row_stride == 0)
4100 row_stride = (png_int_32)/*SAFE*/png_row_stride;
4103 check = -row_stride;
4108 /* This verifies 'check', the absolute value of the actual stride
4109 * passed in and detects overflow in the application calculation (i.e.
4110 * if the app did actually pass in a non-zero 'row_stride'.
4112 if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4114 /* Now check for overflow of the image buffer calculation; this
4115 * limits the whole image size to 32 bits for API compatibility with
4116 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4118 * The PNG_IMAGE_BUFFER_SIZE macro is:
4120 * (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4122 * And the component size is always 1 or 2, so make sure that the
4123 * number of *bytes* that the application is saying are available
4124 * does actually fit into a 32-bit number.
4126 * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4127 * will be changed to use png_alloc_size_t; bigger images can be
4128 * accomodated on 64-bit systems.
4130 if (image->height <=
4131 0xFFFFFFFFU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4133 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4134 (image->colormap_entries > 0 && colormap != NULL))
4137 png_image_read_control display;
4139 memset(&display, 0, (sizeof display));
4140 display.image = image;
4141 display.buffer = buffer;
4142 display.row_stride = row_stride;
4143 display.colormap = colormap;
4144 display.background = background;
4145 display.local_row = NULL;
4147 /* Choose the correct 'end' routine; for the color-map case
4148 * all the setup has already been done.
4150 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4152 png_safe_execute(image,
4153 png_image_read_colormap, &display) &&
4154 png_safe_execute(image,
4155 png_image_read_colormapped, &display);
4159 png_safe_execute(image,
4160 png_image_read_direct, &display);
4162 png_image_free(image);
4167 return png_image_error(image,
4168 "png_image_finish_read[color-map]: no color-map");
4172 return png_image_error(image,
4173 "png_image_finish_read: image too large");
4177 return png_image_error(image,
4178 "png_image_finish_read: invalid argument");
4182 return png_image_error(image,
4183 "png_image_finish_read: row_stride too large");
4186 else if (image != NULL)
4187 return png_image_error(image,
4188 "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4193 #endif /* SIMPLIFIED_READ */