2 /* pngread.c - read a PNG file
4 * Copyright (c) 2018 Cosmin Truta
5 * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson
6 * Copyright (c) 1996-1997 Andreas Dilger
7 * 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_eXIf_SUPPORTED
179 else if (chunk_name == png_eXIf)
180 png_handle_eXIf(png_ptr, info_ptr, length);
183 #ifdef PNG_READ_gAMA_SUPPORTED
184 else if (chunk_name == png_gAMA)
185 png_handle_gAMA(png_ptr, info_ptr, length);
188 #ifdef PNG_READ_hIST_SUPPORTED
189 else if (chunk_name == png_hIST)
190 png_handle_hIST(png_ptr, info_ptr, length);
193 #ifdef PNG_READ_oFFs_SUPPORTED
194 else if (chunk_name == png_oFFs)
195 png_handle_oFFs(png_ptr, info_ptr, length);
198 #ifdef PNG_READ_pCAL_SUPPORTED
199 else if (chunk_name == png_pCAL)
200 png_handle_pCAL(png_ptr, info_ptr, length);
203 #ifdef PNG_READ_sCAL_SUPPORTED
204 else if (chunk_name == png_sCAL)
205 png_handle_sCAL(png_ptr, info_ptr, length);
208 #ifdef PNG_READ_pHYs_SUPPORTED
209 else if (chunk_name == png_pHYs)
210 png_handle_pHYs(png_ptr, info_ptr, length);
213 #ifdef PNG_READ_sBIT_SUPPORTED
214 else if (chunk_name == png_sBIT)
215 png_handle_sBIT(png_ptr, info_ptr, length);
218 #ifdef PNG_READ_sRGB_SUPPORTED
219 else if (chunk_name == png_sRGB)
220 png_handle_sRGB(png_ptr, info_ptr, length);
223 #ifdef PNG_READ_iCCP_SUPPORTED
224 else if (chunk_name == png_iCCP)
225 png_handle_iCCP(png_ptr, info_ptr, length);
228 #ifdef PNG_READ_sPLT_SUPPORTED
229 else if (chunk_name == png_sPLT)
230 png_handle_sPLT(png_ptr, info_ptr, length);
233 #ifdef PNG_READ_tEXt_SUPPORTED
234 else if (chunk_name == png_tEXt)
235 png_handle_tEXt(png_ptr, info_ptr, length);
238 #ifdef PNG_READ_tIME_SUPPORTED
239 else if (chunk_name == png_tIME)
240 png_handle_tIME(png_ptr, info_ptr, length);
243 #ifdef PNG_READ_tRNS_SUPPORTED
244 else if (chunk_name == png_tRNS)
245 png_handle_tRNS(png_ptr, info_ptr, length);
248 #ifdef PNG_READ_zTXt_SUPPORTED
249 else if (chunk_name == png_zTXt)
250 png_handle_zTXt(png_ptr, info_ptr, length);
253 #ifdef PNG_READ_iTXt_SUPPORTED
254 else if (chunk_name == png_iTXt)
255 png_handle_iTXt(png_ptr, info_ptr, length);
259 png_handle_unknown(png_ptr, info_ptr, length,
260 PNG_HANDLE_CHUNK_AS_DEFAULT);
263 #endif /* SEQUENTIAL_READ */
265 /* Optional call to update the users info_ptr structure */
267 png_read_update_info(png_structrp png_ptr, png_inforp info_ptr)
269 png_debug(1, "in png_read_update_info");
273 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
275 png_read_start_row(png_ptr);
277 # ifdef PNG_READ_TRANSFORMS_SUPPORTED
278 png_read_transform_info(png_ptr, info_ptr);
284 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
286 png_app_error(png_ptr,
287 "png_read_update_info/png_start_read_image: duplicate call");
291 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
292 /* Initialize palette, background, etc, after transformations
293 * are set, but before any reading takes place. This allows
294 * the user to obtain a gamma-corrected palette, for example.
295 * If the user doesn't call this, we will do it ourselves.
298 png_start_read_image(png_structrp png_ptr)
300 png_debug(1, "in png_start_read_image");
304 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
305 png_read_start_row(png_ptr);
307 /* New in 1.6.0 this avoids the bug of doing the initializations twice */
309 png_app_error(png_ptr,
310 "png_start_read_image/png_read_update_info: duplicate call");
313 #endif /* SEQUENTIAL_READ */
315 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
316 #ifdef PNG_MNG_FEATURES_SUPPORTED
317 /* Undoes intrapixel differencing,
318 * NOTE: this is apparently only supported in the 'sequential' reader.
321 png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
323 png_debug(1, "in png_do_read_intrapixel");
326 (row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
329 png_uint_32 row_width = row_info->width;
331 if (row_info->bit_depth == 8)
336 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
339 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
345 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
347 *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff);
348 *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff);
351 else if (row_info->bit_depth == 16)
356 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
359 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
365 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
367 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
368 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
369 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
370 png_uint_32 red = (s0 + s1 + 65536) & 0xffff;
371 png_uint_32 blue = (s2 + s1 + 65536) & 0xffff;
372 *(rp ) = (png_byte)((red >> 8) & 0xff);
373 *(rp + 1) = (png_byte)(red & 0xff);
374 *(rp + 4) = (png_byte)((blue >> 8) & 0xff);
375 *(rp + 5) = (png_byte)(blue & 0xff);
380 #endif /* MNG_FEATURES */
383 png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row)
385 png_row_info row_info;
390 png_debug2(1, "in png_read_row (row %lu, pass %d)",
391 (unsigned long)png_ptr->row_number, png_ptr->pass);
393 /* png_read_start_row sets the information (in particular iwidth) for this
396 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
397 png_read_start_row(png_ptr);
399 /* 1.5.6: row_info moved out of png_struct to a local here. */
400 row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */
401 row_info.color_type = png_ptr->color_type;
402 row_info.bit_depth = png_ptr->bit_depth;
403 row_info.channels = png_ptr->channels;
404 row_info.pixel_depth = png_ptr->pixel_depth;
405 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
407 #ifdef PNG_WARNINGS_SUPPORTED
408 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
410 /* Check for transforms that have been set but were defined out */
411 #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
412 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
413 png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined");
416 #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
417 if ((png_ptr->transformations & PNG_FILLER) != 0)
418 png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined");
421 #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
422 !defined(PNG_READ_PACKSWAP_SUPPORTED)
423 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
424 png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined");
427 #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
428 if ((png_ptr->transformations & PNG_PACK) != 0)
429 png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined");
432 #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
433 if ((png_ptr->transformations & PNG_SHIFT) != 0)
434 png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined");
437 #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
438 if ((png_ptr->transformations & PNG_BGR) != 0)
439 png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined");
442 #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
443 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
444 png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined");
447 #endif /* WARNINGS */
449 #ifdef PNG_READ_INTERLACING_SUPPORTED
450 /* If interlaced and we do not need a new row, combine row and return.
451 * Notice that the pixels we have from previous rows have been transformed
452 * already; we can only combine like with like (transformed or
453 * untransformed) and, because of the libpng API for interlaced images, this
454 * means we must transform before de-interlacing.
456 if (png_ptr->interlaced != 0 &&
457 (png_ptr->transformations & PNG_INTERLACE) != 0)
459 switch (png_ptr->pass)
462 if (png_ptr->row_number & 0x07)
465 png_combine_row(png_ptr, dsp_row, 1/*display*/);
466 png_read_finish_row(png_ptr);
472 if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
475 png_combine_row(png_ptr, dsp_row, 1/*display*/);
477 png_read_finish_row(png_ptr);
483 if ((png_ptr->row_number & 0x07) != 4)
485 if (dsp_row != NULL && (png_ptr->row_number & 4))
486 png_combine_row(png_ptr, dsp_row, 1/*display*/);
488 png_read_finish_row(png_ptr);
494 if ((png_ptr->row_number & 3) || png_ptr->width < 3)
497 png_combine_row(png_ptr, dsp_row, 1/*display*/);
499 png_read_finish_row(png_ptr);
505 if ((png_ptr->row_number & 3) != 2)
507 if (dsp_row != NULL && (png_ptr->row_number & 2))
508 png_combine_row(png_ptr, dsp_row, 1/*display*/);
510 png_read_finish_row(png_ptr);
516 if ((png_ptr->row_number & 1) || png_ptr->width < 2)
519 png_combine_row(png_ptr, dsp_row, 1/*display*/);
521 png_read_finish_row(png_ptr);
528 if ((png_ptr->row_number & 1) == 0)
530 png_read_finish_row(png_ptr);
538 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
539 png_error(png_ptr, "Invalid attempt to read row data");
541 /* Fill the row with IDAT data: */
542 png_ptr->row_buf[0]=255; /* to force error if no data was found */
543 png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1);
545 if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE)
547 if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST)
548 png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1,
549 png_ptr->prev_row + 1, png_ptr->row_buf[0]);
551 png_error(png_ptr, "bad adaptive filter value");
554 /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before
555 * 1.5.6, while the buffer really is this big in current versions of libpng
556 * it may not be in the future, so this was changed just to copy the
559 memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1);
561 #ifdef PNG_MNG_FEATURES_SUPPORTED
562 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
563 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
565 /* Intrapixel differencing */
566 png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1);
570 #ifdef PNG_READ_TRANSFORMS_SUPPORTED
571 if (png_ptr->transformations)
572 png_do_read_transformations(png_ptr, &row_info);
575 /* The transformed pixel depth should match the depth now in row_info. */
576 if (png_ptr->transformed_pixel_depth == 0)
578 png_ptr->transformed_pixel_depth = row_info.pixel_depth;
579 if (row_info.pixel_depth > png_ptr->maximum_pixel_depth)
580 png_error(png_ptr, "sequential row overflow");
583 else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth)
584 png_error(png_ptr, "internal sequential row size calculation error");
586 #ifdef PNG_READ_INTERLACING_SUPPORTED
587 /* Expand interlaced rows to full size */
588 if (png_ptr->interlaced != 0 &&
589 (png_ptr->transformations & PNG_INTERLACE) != 0)
591 if (png_ptr->pass < 6)
592 png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass,
593 png_ptr->transformations);
596 png_combine_row(png_ptr, dsp_row, 1/*display*/);
599 png_combine_row(png_ptr, row, 0/*row*/);
606 png_combine_row(png_ptr, row, -1/*ignored*/);
609 png_combine_row(png_ptr, dsp_row, -1/*ignored*/);
611 png_read_finish_row(png_ptr);
613 if (png_ptr->read_row_fn != NULL)
614 (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
617 #endif /* SEQUENTIAL_READ */
619 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
620 /* Read one or more rows of image data. If the image is interlaced,
621 * and png_set_interlace_handling() has been called, the rows need to
622 * contain the contents of the rows from the previous pass. If the
623 * image has alpha or transparency, and png_handle_alpha()[*] has been
624 * called, the rows contents must be initialized to the contents of the
627 * "row" holds the actual image, and pixels are placed in it
628 * as they arrive. If the image is displayed after each pass, it will
629 * appear to "sparkle" in. "display_row" can be used to display a
630 * "chunky" progressive image, with finer detail added as it becomes
631 * available. If you do not want this "chunky" display, you may pass
632 * NULL for display_row. If you do not want the sparkle display, and
633 * you have not called png_handle_alpha(), you may pass NULL for rows.
634 * If you have called png_handle_alpha(), and the image has either an
635 * alpha channel or a transparency chunk, you must provide a buffer for
636 * rows. In this case, you do not have to provide a display_row buffer
637 * also, but you may. If the image is not interlaced, or if you have
638 * not called png_set_interlace_handling(), the display_row buffer will
639 * be ignored, so pass NULL to it.
641 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
645 png_read_rows(png_structrp png_ptr, png_bytepp row,
646 png_bytepp display_row, png_uint_32 num_rows)
652 png_debug(1, "in png_read_rows");
659 if (rp != NULL && dp != NULL)
660 for (i = 0; i < num_rows; i++)
662 png_bytep rptr = *rp++;
663 png_bytep dptr = *dp++;
665 png_read_row(png_ptr, rptr, dptr);
669 for (i = 0; i < num_rows; i++)
671 png_bytep rptr = *rp;
672 png_read_row(png_ptr, rptr, NULL);
677 for (i = 0; i < num_rows; i++)
679 png_bytep dptr = *dp;
680 png_read_row(png_ptr, NULL, dptr);
684 #endif /* SEQUENTIAL_READ */
686 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
687 /* Read the entire image. If the image has an alpha channel or a tRNS
688 * chunk, and you have called png_handle_alpha()[*], you will need to
689 * initialize the image to the current image that PNG will be overlaying.
690 * We set the num_rows again here, in case it was incorrectly set in
691 * png_read_start_row() by a call to png_read_update_info() or
692 * png_start_read_image() if png_set_interlace_handling() wasn't called
693 * prior to either of these functions like it should have been. You can
694 * only call this function once. If you desire to have an image for
695 * each pass of a interlaced image, use png_read_rows() instead.
697 * [*] png_handle_alpha() does not exist yet, as of this version of libpng
700 png_read_image(png_structrp png_ptr, png_bytepp image)
702 png_uint_32 i, image_height;
706 png_debug(1, "in png_read_image");
711 #ifdef PNG_READ_INTERLACING_SUPPORTED
712 if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0)
714 pass = png_set_interlace_handling(png_ptr);
715 /* And make sure transforms are initialized. */
716 png_start_read_image(png_ptr);
720 if (png_ptr->interlaced != 0 &&
721 (png_ptr->transformations & PNG_INTERLACE) == 0)
723 /* Caller called png_start_read_image or png_read_update_info without
724 * first turning on the PNG_INTERLACE transform. We can fix this here,
725 * but the caller should do it!
727 png_warning(png_ptr, "Interlace handling should be turned on when "
728 "using png_read_image");
729 /* Make sure this is set correctly */
730 png_ptr->num_rows = png_ptr->height;
733 /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
734 * the above error case.
736 pass = png_set_interlace_handling(png_ptr);
739 if (png_ptr->interlaced)
741 "Cannot read interlaced image -- interlace handler disabled");
746 image_height=png_ptr->height;
748 for (j = 0; j < pass; j++)
751 for (i = 0; i < image_height; i++)
753 png_read_row(png_ptr, *rp, NULL);
759 #ifdef _PNG_COLOR_PICK_ENABLED_
761 png_read_image_with_pick_color(png_structp png_ptr, png_bytepp image, PngPickColor *pickcolor)
763 png_uint_32 i, image_height;
765 png_uint_32 /*k = 0,*/ image_bpp = 0, image_width;
768 unsigned int npixels;
769 int perc_enable_y1, perc_enable_y2;
770 png_debug(1, "in png_read_image");
772 if (png_ptr == NULL || pickcolor == NULL)
775 #ifdef PNG_READ_INTERLACING_SUPPORTED
776 if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
778 pass = png_set_interlace_handling(png_ptr);
779 /* And make sure transforms are initialized. */
780 png_start_read_image(png_ptr);
784 if (png_ptr->interlaced && !(png_ptr->transformations & PNG_INTERLACE))
786 /* Caller called png_start_read_image or png_read_update_info without
787 * first turning on the PNG_INTERLACE transform. We can fix this here,
788 * but the caller should do it!
790 png_warning(png_ptr, "Interlace handling should be turned on when "
791 "using png_read_image");
792 /* Make sure this is set correctly */
793 png_ptr->num_rows = png_ptr->height;
796 /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in
797 * the above error case.
799 pass = png_set_interlace_handling(png_ptr);
802 if (png_ptr->interlaced)
804 "Cannot read interlaced image -- interlace handler disabled");
809 image_height=png_ptr->height;
810 image_bpp=png_ptr->rowbytes;
811 image_width=png_ptr->width;
812 png_ptr->user_chunk_ptr = pickcolor;
814 if(pickcolor->perc < 0)
816 png_error(png_ptr, "ColorPick percentage is negative");
819 if( (pickcolor->region < PNG_COLORPICK_TOP) || (pickcolor->region > PNG_COLORPICK_BOTTOM))
821 png_error(png_ptr, "ColorPick Region is out of bound");
824 if(pickcolor->region == PNG_COLORPICK_TOP)
827 perc_enable_y2 = (pickcolor->perc*image_height/100) - 1;
829 else if(pickcolor->region == PNG_COLORPICK_MIDDLE)
831 perc_enable_y1 = (image_height/2) - (((pickcolor->perc/2)*image_height)/100);
832 perc_enable_y2 = perc_enable_y1 + ((pickcolor->perc*image_height)/100) - 1;
836 perc_enable_y1 = (image_height) - ( pickcolor->perc * image_height / 100 );
837 perc_enable_y2 = image_height - 1;
840 for (j = 0; j < pass; j++)
843 for (i = 0; i < image_height; i++)
845 pickcolor->enable = 0;
846 if( pickcolor->perc > 0 )
848 if( (int)i >= perc_enable_y1 && (int)i <= perc_enable_y2)
850 pickcolor->enable = 1;
855 if( ((int)i >= pickcolor->y1) && ((int)i <= pickcolor->y2) )
857 pickcolor->enable = 1;
860 png_read_row(png_ptr, *rp, NULL);
866 if(pickcolor->perc > 0)
868 npixels = (pickcolor->perc*image_height*image_width)/100;
872 npixels = (pickcolor->x2-pickcolor->x1+1)*(pickcolor->y2-pickcolor->y1+1);
876 pickcolor->sumR = pickcolor->sumR/npixels;
877 pickcolor->sumG = pickcolor->sumG/npixels;
878 pickcolor->sumB = pickcolor->sumB/npixels;
881 #endif /* _PNG_COLOR_PICK_ENABLED_ */
882 #endif /* SEQUENTIAL_READ */
884 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
885 /* Read the end of the PNG file. Will not read past the end of the
886 * file, will verify the end is accurate, and will read any comments
887 * or time information at the end of the file, if info is not NULL.
890 png_read_end(png_structrp png_ptr, png_inforp info_ptr)
892 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
896 png_debug(1, "in png_read_end");
901 /* If png_read_end is called in the middle of reading the rows there may
902 * still be pending IDAT data and an owned zstream. Deal with this here.
904 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
905 if (png_chunk_unknown_handling(png_ptr, png_IDAT) == 0)
907 png_read_finish_IDAT(png_ptr);
909 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
910 /* Report invalid palette index; added at libng-1.5.10 */
911 if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
912 png_ptr->num_palette_max > png_ptr->num_palette)
913 png_benign_error(png_ptr, "Read palette index exceeding num_palette");
918 png_uint_32 length = png_read_chunk_header(png_ptr);
919 png_uint_32 chunk_name = png_ptr->chunk_name;
921 if (chunk_name != png_IDAT)
922 png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
924 if (chunk_name == png_IEND)
925 png_handle_IEND(png_ptr, info_ptr, length);
927 else if (chunk_name == png_IHDR)
928 png_handle_IHDR(png_ptr, info_ptr, length);
930 else if (info_ptr == NULL)
931 png_crc_finish(png_ptr, length);
933 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
934 else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0)
936 if (chunk_name == png_IDAT)
938 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
939 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
940 png_benign_error(png_ptr, ".Too many IDATs found");
942 png_handle_unknown(png_ptr, info_ptr, length, keep);
943 if (chunk_name == png_PLTE)
944 png_ptr->mode |= PNG_HAVE_PLTE;
948 else if (chunk_name == png_IDAT)
950 /* Zero length IDATs are legal after the last IDAT has been
951 * read, but not after other chunks have been read. 1.6 does not
952 * always read all the deflate data; specifically it cannot be relied
953 * upon to read the Adler32 at the end. If it doesn't ignore IDAT
954 * chunks which are longer than zero as well:
956 if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
957 || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
958 png_benign_error(png_ptr, "..Too many IDATs found");
960 png_crc_finish(png_ptr, length);
962 else if (chunk_name == png_PLTE)
963 png_handle_PLTE(png_ptr, info_ptr, length);
965 #ifdef PNG_READ_bKGD_SUPPORTED
966 else if (chunk_name == png_bKGD)
967 png_handle_bKGD(png_ptr, info_ptr, length);
970 #ifdef PNG_READ_cHRM_SUPPORTED
971 else if (chunk_name == png_cHRM)
972 png_handle_cHRM(png_ptr, info_ptr, length);
975 #ifdef PNG_READ_eXIf_SUPPORTED
976 else if (chunk_name == png_eXIf)
977 png_handle_eXIf(png_ptr, info_ptr, length);
980 #ifdef PNG_READ_gAMA_SUPPORTED
981 else if (chunk_name == png_gAMA)
982 png_handle_gAMA(png_ptr, info_ptr, length);
985 #ifdef PNG_READ_hIST_SUPPORTED
986 else if (chunk_name == png_hIST)
987 png_handle_hIST(png_ptr, info_ptr, length);
990 #ifdef PNG_READ_oFFs_SUPPORTED
991 else if (chunk_name == png_oFFs)
992 png_handle_oFFs(png_ptr, info_ptr, length);
995 #ifdef PNG_READ_pCAL_SUPPORTED
996 else if (chunk_name == png_pCAL)
997 png_handle_pCAL(png_ptr, info_ptr, length);
1000 #ifdef PNG_READ_sCAL_SUPPORTED
1001 else if (chunk_name == png_sCAL)
1002 png_handle_sCAL(png_ptr, info_ptr, length);
1005 #ifdef PNG_READ_pHYs_SUPPORTED
1006 else if (chunk_name == png_pHYs)
1007 png_handle_pHYs(png_ptr, info_ptr, length);
1010 #ifdef PNG_READ_sBIT_SUPPORTED
1011 else if (chunk_name == png_sBIT)
1012 png_handle_sBIT(png_ptr, info_ptr, length);
1015 #ifdef PNG_READ_sRGB_SUPPORTED
1016 else if (chunk_name == png_sRGB)
1017 png_handle_sRGB(png_ptr, info_ptr, length);
1020 #ifdef PNG_READ_iCCP_SUPPORTED
1021 else if (chunk_name == png_iCCP)
1022 png_handle_iCCP(png_ptr, info_ptr, length);
1025 #ifdef PNG_READ_sPLT_SUPPORTED
1026 else if (chunk_name == png_sPLT)
1027 png_handle_sPLT(png_ptr, info_ptr, length);
1030 #ifdef PNG_READ_tEXt_SUPPORTED
1031 else if (chunk_name == png_tEXt)
1032 png_handle_tEXt(png_ptr, info_ptr, length);
1035 #ifdef PNG_READ_tIME_SUPPORTED
1036 else if (chunk_name == png_tIME)
1037 png_handle_tIME(png_ptr, info_ptr, length);
1040 #ifdef PNG_READ_tRNS_SUPPORTED
1041 else if (chunk_name == png_tRNS)
1042 png_handle_tRNS(png_ptr, info_ptr, length);
1045 #ifdef PNG_READ_zTXt_SUPPORTED
1046 else if (chunk_name == png_zTXt)
1047 png_handle_zTXt(png_ptr, info_ptr, length);
1050 #ifdef PNG_READ_iTXt_SUPPORTED
1051 else if (chunk_name == png_iTXt)
1052 png_handle_iTXt(png_ptr, info_ptr, length);
1056 png_handle_unknown(png_ptr, info_ptr, length,
1057 PNG_HANDLE_CHUNK_AS_DEFAULT);
1058 } while ((png_ptr->mode & PNG_HAVE_IEND) == 0);
1060 #endif /* SEQUENTIAL_READ */
1062 /* Free all memory used in the read struct */
1064 png_read_destroy(png_structrp png_ptr)
1066 png_debug(1, "in png_read_destroy");
1068 #ifdef PNG_READ_GAMMA_SUPPORTED
1069 png_destroy_gamma_table(png_ptr);
1072 png_free(png_ptr, png_ptr->big_row_buf);
1073 png_ptr->big_row_buf = NULL;
1074 png_free(png_ptr, png_ptr->big_prev_row);
1075 png_ptr->big_prev_row = NULL;
1076 png_free(png_ptr, png_ptr->read_buffer);
1077 png_ptr->read_buffer = NULL;
1079 #ifdef PNG_READ_QUANTIZE_SUPPORTED
1080 png_free(png_ptr, png_ptr->palette_lookup);
1081 png_ptr->palette_lookup = NULL;
1082 png_free(png_ptr, png_ptr->quantize_index);
1083 png_ptr->quantize_index = NULL;
1086 if ((png_ptr->free_me & PNG_FREE_PLTE) != 0)
1088 png_zfree(png_ptr, png_ptr->palette);
1089 png_ptr->palette = NULL;
1091 png_ptr->free_me &= ~PNG_FREE_PLTE;
1093 #if defined(PNG_tRNS_SUPPORTED) || \
1094 defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
1095 if ((png_ptr->free_me & PNG_FREE_TRNS) != 0)
1097 png_free(png_ptr, png_ptr->trans_alpha);
1098 png_ptr->trans_alpha = NULL;
1100 png_ptr->free_me &= ~PNG_FREE_TRNS;
1103 inflateEnd(&png_ptr->zstream);
1105 #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
1106 png_free(png_ptr, png_ptr->save_buffer);
1107 png_ptr->save_buffer = NULL;
1110 #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) && \
1111 defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
1112 png_free(png_ptr, png_ptr->unknown_chunk.data);
1113 png_ptr->unknown_chunk.data = NULL;
1116 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
1117 png_free(png_ptr, png_ptr->chunk_list);
1118 png_ptr->chunk_list = NULL;
1121 /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
1122 * callbacks are still set at this point. They are required to complete the
1123 * destruction of the png_struct itself.
1127 /* Free all memory used by the read */
1129 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
1130 png_infopp end_info_ptr_ptr)
1132 png_structrp png_ptr = NULL;
1134 png_debug(1, "in png_destroy_read_struct");
1136 if (png_ptr_ptr != NULL)
1137 png_ptr = *png_ptr_ptr;
1139 if (png_ptr == NULL)
1142 /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1143 * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1144 * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1146 png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1147 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1149 *png_ptr_ptr = NULL;
1150 png_read_destroy(png_ptr);
1151 png_destroy_png_struct(png_ptr);
1155 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1157 if (png_ptr == NULL)
1160 png_ptr->read_row_fn = read_row_fn;
1164 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1165 #ifdef PNG_INFO_IMAGE_SUPPORTED
1167 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1168 int transforms, voidp params)
1170 if (png_ptr == NULL || info_ptr == NULL)
1173 /* png_read_info() gives us all of the information from the
1174 * PNG file before the first IDAT (image data chunk).
1176 png_read_info(png_ptr, info_ptr);
1177 if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1178 png_error(png_ptr, "Image is too high to process with png_read_png()");
1180 /* -------------- image transformations start here ------------------- */
1181 /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1182 * is not implemented. This will only happen in de-configured (non-default)
1183 * libpng builds. The results can be unexpected - png_read_png may return
1184 * short or mal-formed rows because the transform is skipped.
1187 /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1189 if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1190 /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1191 * did in earlier versions, while "scale_16" is now more accurate.
1193 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1194 png_set_scale_16(png_ptr);
1196 png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1199 /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1200 * latter by doing SCALE first. This is ok and allows apps not to check for
1201 * which is supported to get the right answer.
1203 if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1204 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1205 png_set_strip_16(png_ptr);
1207 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1210 /* Strip alpha bytes from the input data without combining with
1211 * the background (not recommended).
1213 if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1214 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1215 png_set_strip_alpha(png_ptr);
1217 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1220 /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1221 * byte into separate bytes (useful for paletted and grayscale images).
1223 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1224 #ifdef PNG_READ_PACK_SUPPORTED
1225 png_set_packing(png_ptr);
1227 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1230 /* Change the order of packed pixels to least significant bit first
1231 * (not useful if you are using png_set_packing).
1233 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1234 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1235 png_set_packswap(png_ptr);
1237 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1240 /* Expand paletted colors into true RGB triplets
1241 * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1242 * Expand paletted or RGB images with transparency to full alpha
1243 * channels so the data will be available as RGBA quartets.
1245 if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1246 #ifdef PNG_READ_EXPAND_SUPPORTED
1247 png_set_expand(png_ptr);
1249 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1252 /* We don't handle background color or gamma transformation or quantizing.
1255 /* Invert monochrome files to have 0 as white and 1 as black
1257 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1258 #ifdef PNG_READ_INVERT_SUPPORTED
1259 png_set_invert_mono(png_ptr);
1261 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1264 /* If you want to shift the pixel values from the range [0,255] or
1265 * [0,65535] to the original [0,7] or [0,31], or whatever range the
1266 * colors were originally in:
1268 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1269 #ifdef PNG_READ_SHIFT_SUPPORTED
1270 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1271 png_set_shift(png_ptr, &info_ptr->sig_bit);
1273 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1276 /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1277 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1278 #ifdef PNG_READ_BGR_SUPPORTED
1279 png_set_bgr(png_ptr);
1281 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1284 /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1285 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1286 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1287 png_set_swap_alpha(png_ptr);
1289 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1292 /* Swap bytes of 16-bit files to least significant byte first */
1293 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1294 #ifdef PNG_READ_SWAP_SUPPORTED
1295 png_set_swap(png_ptr);
1297 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1300 /* Added at libpng-1.2.41 */
1301 /* Invert the alpha channel from opacity to transparency */
1302 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1303 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1304 png_set_invert_alpha(png_ptr);
1306 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1309 /* Added at libpng-1.2.41 */
1310 /* Expand grayscale image to RGB */
1311 if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1312 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1313 png_set_gray_to_rgb(png_ptr);
1315 png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1318 /* Added at libpng-1.5.4 */
1319 if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1320 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1321 png_set_expand_16(png_ptr);
1323 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1326 /* We don't handle adding filler bytes */
1328 /* We use png_read_image and rely on that for interlace handling, but we also
1329 * call png_read_update_info therefore must turn on interlace handling now:
1331 (void)png_set_interlace_handling(png_ptr);
1333 /* Optional call to gamma correct and add the background to the palette
1334 * and update info structure. REQUIRED if you are expecting libpng to
1335 * update the palette for you (i.e., you selected such a transform above).
1337 png_read_update_info(png_ptr, info_ptr);
1339 /* -------------- image transformations end here ------------------- */
1341 png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1342 if (info_ptr->row_pointers == NULL)
1346 info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1347 info_ptr->height * (sizeof (png_bytep))));
1349 for (iptr=0; iptr<info_ptr->height; iptr++)
1350 info_ptr->row_pointers[iptr] = NULL;
1352 info_ptr->free_me |= PNG_FREE_ROWS;
1354 for (iptr = 0; iptr < info_ptr->height; iptr++)
1355 info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1356 png_malloc(png_ptr, info_ptr->rowbytes));
1359 png_read_image(png_ptr, info_ptr->row_pointers);
1360 info_ptr->valid |= PNG_INFO_IDAT;
1362 /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1363 png_read_end(png_ptr, info_ptr);
1367 #endif /* INFO_IMAGE */
1368 #endif /* SEQUENTIAL_READ */
1370 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1373 * This code currently relies on the sequential reader, though it could easily
1374 * be made to work with the progressive one.
1376 /* Arguments to png_image_finish_read: */
1378 /* Encoding of PNG data (used by the color-map code) */
1379 # define P_NOTSET 0 /* File encoding not yet known */
1380 # define P_sRGB 1 /* 8-bit encoded to sRGB gamma */
1381 # define P_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1382 # define P_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */
1383 # define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1385 /* Color-map processing: after libpng has run on the PNG image further
1386 * processing may be needed to convert the data to color-map indices.
1388 #define PNG_CMAP_NONE 0
1389 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */
1390 #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */
1391 #define PNG_CMAP_RGB 3 /* Process RGB data */
1392 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1394 /* The following document where the background is for each processing case. */
1395 #define PNG_CMAP_NONE_BACKGROUND 256
1396 #define PNG_CMAP_GA_BACKGROUND 231
1397 #define PNG_CMAP_TRANS_BACKGROUND 254
1398 #define PNG_CMAP_RGB_BACKGROUND 256
1399 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1406 png_int_32 row_stride;
1408 png_const_colorp background;
1409 /* Local variables: */
1410 png_voidp local_row;
1411 png_voidp first_row;
1412 ptrdiff_t row_bytes; /* step between rows */
1413 int file_encoding; /* E_ values above */
1414 png_fixed_point gamma_to_linear; /* For P_FILE, reciprocal of gamma */
1415 int colormap_processing; /* PNG_CMAP_ values above */
1416 } png_image_read_control;
1418 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1419 * called, so setting up the jmp_buf is not required. This means that anything
1420 * called from here must *not* call png_malloc - it has to call png_malloc_warn
1421 * instead so that control is returned safely back to this routine.
1424 png_image_read_init(png_imagep image)
1426 if (image->opaque == NULL)
1428 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1429 png_safe_error, png_safe_warning);
1431 /* And set the rest of the structure to NULL to ensure that the various
1432 * fields are consistent.
1434 memset(image, 0, (sizeof *image));
1435 image->version = PNG_IMAGE_VERSION;
1437 if (png_ptr != NULL)
1439 png_infop info_ptr = png_create_info_struct(png_ptr);
1441 if (info_ptr != NULL)
1443 png_controlp control = png_voidcast(png_controlp,
1444 png_malloc_warn(png_ptr, (sizeof *control)));
1446 if (control != NULL)
1448 memset(control, 0, (sizeof *control));
1450 control->png_ptr = png_ptr;
1451 control->info_ptr = info_ptr;
1452 control->for_write = 0;
1454 image->opaque = control;
1458 /* Error clean up */
1459 png_destroy_info_struct(png_ptr, &info_ptr);
1462 png_destroy_read_struct(&png_ptr, NULL, NULL);
1465 return png_image_error(image, "png_image_read: out of memory");
1468 return png_image_error(image, "png_image_read: opaque pointer not NULL");
1471 /* Utility to find the base format of a PNG file from a png_struct. */
1473 png_image_format(png_structrp png_ptr)
1475 png_uint_32 format = 0;
1477 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1478 format |= PNG_FORMAT_FLAG_COLOR;
1480 if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1481 format |= PNG_FORMAT_FLAG_ALPHA;
1483 /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1484 * sets the png_struct fields; that's all we are interested in here. The
1485 * precise interaction with an app call to png_set_tRNS and PNG file reading
1488 else if (png_ptr->num_trans > 0)
1489 format |= PNG_FORMAT_FLAG_ALPHA;
1491 if (png_ptr->bit_depth == 16)
1492 format |= PNG_FORMAT_FLAG_LINEAR;
1494 if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1495 format |= PNG_FORMAT_FLAG_COLORMAP;
1500 /* Is the given gamma significantly different from sRGB? The test is the same
1501 * one used in pngrtran.c when deciding whether to do gamma correction. The
1502 * arithmetic optimizes the division by using the fact that the inverse of the
1503 * file sRGB gamma is 2.2
1506 png_gamma_not_sRGB(png_fixed_point g)
1510 /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1514 return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1520 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1521 * header and fill in all the information. This is executed in a safe context,
1522 * unlike the init routine above.
1525 png_image_read_header(png_voidp argument)
1527 png_imagep image = png_voidcast(png_imagep, argument);
1528 png_structrp png_ptr = image->opaque->png_ptr;
1529 png_inforp info_ptr = image->opaque->info_ptr;
1531 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1532 png_set_benign_errors(png_ptr, 1/*warn*/);
1534 png_read_info(png_ptr, info_ptr);
1536 /* Do this the fast way; just read directly out of png_struct. */
1537 image->width = png_ptr->width;
1538 image->height = png_ptr->height;
1541 png_uint_32 format = png_image_format(png_ptr);
1543 image->format = format;
1545 #ifdef PNG_COLORSPACE_SUPPORTED
1546 /* Does the colorspace match sRGB? If there is no color endpoint
1547 * (colorant) information assume yes, otherwise require the
1548 * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set. If the
1549 * colorspace has been determined to be invalid ignore it.
1551 if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1552 & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1553 PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1554 image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1558 /* We need the maximum number of entries regardless of the format the
1559 * application sets here.
1562 png_uint_32 cmap_entries;
1564 switch (png_ptr->color_type)
1566 case PNG_COLOR_TYPE_GRAY:
1567 cmap_entries = 1U << png_ptr->bit_depth;
1570 case PNG_COLOR_TYPE_PALETTE:
1571 cmap_entries = (png_uint_32)png_ptr->num_palette;
1579 if (cmap_entries > 256)
1582 image->colormap_entries = cmap_entries;
1588 #ifdef PNG_STDIO_SUPPORTED
1590 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1592 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1596 if (png_image_read_init(image) != 0)
1598 /* This is slightly evil, but png_init_io doesn't do anything other
1599 * than this and we haven't changed the standard IO functions so
1600 * this saves a 'safe' function.
1602 image->opaque->png_ptr->io_ptr = file;
1603 return png_safe_execute(image, png_image_read_header, image);
1608 return png_image_error(image,
1609 "png_image_begin_read_from_stdio: invalid argument");
1612 else if (image != NULL)
1613 return png_image_error(image,
1614 "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1620 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1622 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1624 if (file_name != NULL)
1626 FILE *fp = fopen(file_name, "rb");
1630 if (png_image_read_init(image) != 0)
1632 image->opaque->png_ptr->io_ptr = fp;
1633 image->opaque->owned_file = 1;
1634 return png_safe_execute(image, png_image_read_header, image);
1637 /* Clean up: just the opened file. */
1642 return png_image_error(image, strerror(errno));
1646 return png_image_error(image,
1647 "png_image_begin_read_from_file: invalid argument");
1650 else if (image != NULL)
1651 return png_image_error(image,
1652 "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1658 static void PNGCBAPI
1659 png_image_memory_read(png_structp png_ptr, png_bytep out, size_t need)
1661 if (png_ptr != NULL)
1663 png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1666 png_controlp cp = image->opaque;
1669 png_const_bytep memory = cp->memory;
1670 size_t size = cp->size;
1672 if (memory != NULL && size >= need)
1674 memcpy(out, memory, need);
1675 cp->memory = memory + need;
1676 cp->size = size - need;
1680 png_error(png_ptr, "read beyond end of data");
1684 png_error(png_ptr, "invalid memory read");
1688 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1689 png_const_voidp memory, size_t size)
1691 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1693 if (memory != NULL && size > 0)
1695 if (png_image_read_init(image) != 0)
1697 /* Now set the IO functions to read from the memory buffer and
1698 * store it into io_ptr. Again do this in-place to avoid calling a
1699 * libpng function that requires error handling.
1701 image->opaque->memory = png_voidcast(png_const_bytep, memory);
1702 image->opaque->size = size;
1703 image->opaque->png_ptr->io_ptr = image;
1704 image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1706 return png_safe_execute(image, png_image_read_header, image);
1711 return png_image_error(image,
1712 "png_image_begin_read_from_memory: invalid argument");
1715 else if (image != NULL)
1716 return png_image_error(image,
1717 "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1722 /* Utility function to skip chunks that are not used by the simplified image
1723 * read functions and an appropriate macro to call it.
1725 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1727 png_image_skip_unused_chunks(png_structrp png_ptr)
1729 /* Prepare the reader to ignore all recognized chunks whose data will not
1730 * be used, i.e., all chunks recognized by libpng except for those
1731 * involved in basic image reading:
1733 * IHDR, PLTE, IDAT, IEND
1735 * Or image data handling:
1737 * tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1739 * This provides a small performance improvement and eliminates any
1740 * potential vulnerability to security problems in the unused chunks.
1742 * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1743 * too. This allows the simplified API to be compiled without iCCP support,
1744 * however if the support is there the chunk is still checked to detect
1745 * errors (which are unfortunately quite common.)
1748 static const png_byte chunks_to_process[] = {
1749 98, 75, 71, 68, '\0', /* bKGD */
1750 99, 72, 82, 77, '\0', /* cHRM */
1751 103, 65, 77, 65, '\0', /* gAMA */
1752 # ifdef PNG_READ_iCCP_SUPPORTED
1753 105, 67, 67, 80, '\0', /* iCCP */
1755 115, 66, 73, 84, '\0', /* sBIT */
1756 115, 82, 71, 66, '\0', /* sRGB */
1759 /* Ignore unknown chunks and all other chunks except for the
1760 * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1762 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1765 /* But do not ignore image data handling chunks */
1766 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1767 chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1771 # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1773 # define PNG_SKIP_CHUNKS(p) ((void)0)
1774 #endif /* HANDLE_AS_UNKNOWN */
1776 /* The following macro gives the exact rounded answer for all values in the
1777 * range 0..255 (it actually divides by 51.2, but the rounding still generates
1778 * the correct numbers 0..5
1780 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1782 /* Utility functions to make particular color-maps */
1784 set_file_encoding(png_image_read_control *display)
1786 png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1787 if (png_gamma_significant(g) != 0)
1789 if (png_gamma_not_sRGB(g) != 0)
1791 display->file_encoding = P_FILE;
1792 display->gamma_to_linear = png_reciprocal(g);
1796 display->file_encoding = P_sRGB;
1800 display->file_encoding = P_LINEAR8;
1804 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1806 if (encoding == P_FILE) /* double check */
1807 encoding = display->file_encoding;
1809 if (encoding == P_NOTSET) /* must be the file encoding */
1811 set_file_encoding(display);
1812 encoding = display->file_encoding;
1818 value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1822 value = png_sRGB_table[value];
1834 png_error(display->image->opaque->png_ptr,
1835 "unexpected encoding (internal error)");
1843 png_colormap_compose(png_image_read_control *display,
1844 png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1845 png_uint_32 background, int encoding)
1847 /* The file value is composed on the background, the background has the given
1848 * encoding and so does the result, the file is encoded with P_FILE and the
1849 * file and alpha are 8-bit values. The (output) encoding will always be
1850 * P_LINEAR or P_sRGB.
1852 png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1853 png_uint_32 b = decode_gamma(display, background, encoding);
1855 /* The alpha is always an 8-bit value (it comes from the palette), the value
1856 * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1858 f = f * alpha + b * (255-alpha);
1860 if (encoding == P_LINEAR)
1862 /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1863 * accurate, it divides by 255.00000005937181414556, with no overflow.)
1865 f *= 257; /* Now scaled by 65535 */
1867 f = (f+32768) >> 16;
1871 f = PNG_sRGB_FROM_LINEAR(f);
1876 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1880 png_create_colormap_entry(png_image_read_control *display,
1881 png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1882 png_uint_32 alpha, int encoding)
1884 png_imagep image = display->image;
1885 int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1887 int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1888 (red != green || green != blue);
1891 png_error(image->opaque->png_ptr, "color-map index out of range");
1893 /* Update the cache with whether the file gamma is significantly different
1896 if (encoding == P_FILE)
1898 if (display->file_encoding == P_NOTSET)
1899 set_file_encoding(display);
1901 /* Note that the cached value may be P_FILE too, but if it is then the
1902 * gamma_to_linear member has been set.
1904 encoding = display->file_encoding;
1907 if (encoding == P_FILE)
1909 png_fixed_point g = display->gamma_to_linear;
1911 red = png_gamma_16bit_correct(red*257, g);
1912 green = png_gamma_16bit_correct(green*257, g);
1913 blue = png_gamma_16bit_correct(blue*257, g);
1915 if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1918 encoding = P_LINEAR;
1923 red = PNG_sRGB_FROM_LINEAR(red * 255);
1924 green = PNG_sRGB_FROM_LINEAR(green * 255);
1925 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1930 else if (encoding == P_LINEAR8)
1932 /* This encoding occurs quite frequently in test cases because PngSuite
1933 * includes a gAMA 1.0 chunk with most images.
1939 encoding = P_LINEAR;
1942 else if (encoding == P_sRGB &&
1943 (convert_to_Y != 0 || output_encoding == P_LINEAR))
1945 /* The values are 8-bit sRGB values, but must be converted to 16-bit
1948 red = png_sRGB_table[red];
1949 green = png_sRGB_table[green];
1950 blue = png_sRGB_table[blue];
1952 encoding = P_LINEAR;
1955 /* This is set if the color isn't gray but the output is. */
1956 if (encoding == P_LINEAR)
1958 if (convert_to_Y != 0)
1960 /* NOTE: these values are copied from png_do_rgb_to_gray */
1961 png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green +
1962 (png_uint_32)2366 * blue;
1964 if (output_encoding == P_LINEAR)
1965 y = (y + 16384) >> 15;
1969 /* y is scaled by 32768, we need it scaled by 255: */
1972 y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1973 alpha = PNG_DIV257(alpha);
1977 blue = red = green = y;
1980 else if (output_encoding == P_sRGB)
1982 red = PNG_sRGB_FROM_LINEAR(red * 255);
1983 green = PNG_sRGB_FROM_LINEAR(green * 255);
1984 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1985 alpha = PNG_DIV257(alpha);
1990 if (encoding != output_encoding)
1991 png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1993 /* Store the value. */
1995 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
1996 int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1997 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
2001 # ifdef PNG_FORMAT_BGR_SUPPORTED
2002 int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
2007 if (output_encoding == P_LINEAR)
2009 png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
2011 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2013 /* The linear 16-bit values must be pre-multiplied by the alpha channel
2014 * value, if less than 65535 (this is, effectively, composite on black
2015 * if the alpha channel is removed.)
2017 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2020 entry[afirst ? 0 : 3] = (png_uint_16)alpha;
2028 blue = (blue * alpha + 32767U)/65535U;
2029 green = (green * alpha + 32767U)/65535U;
2030 red = (red * alpha + 32767U)/65535U;
2034 red = green = blue = 0;
2036 entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
2037 entry[afirst + 1] = (png_uint_16)green;
2038 entry[afirst + bgr] = (png_uint_16)red;
2042 entry[1 ^ afirst] = (png_uint_16)alpha;
2049 green = (green * alpha + 32767U)/65535U;
2054 entry[afirst] = (png_uint_16)green;
2062 else /* output encoding is P_sRGB */
2064 png_bytep entry = png_voidcast(png_bytep, display->colormap);
2066 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2068 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2071 entry[afirst ? 0 : 3] = (png_byte)alpha;
2074 entry[afirst + (2 ^ bgr)] = (png_byte)blue;
2075 entry[afirst + 1] = (png_byte)green;
2076 entry[afirst + bgr] = (png_byte)red;
2080 entry[1 ^ afirst] = (png_byte)alpha;
2083 entry[afirst] = (png_byte)green;
2101 make_gray_file_colormap(png_image_read_control *display)
2105 for (i=0; i<256; ++i)
2106 png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
2112 make_gray_colormap(png_image_read_control *display)
2116 for (i=0; i<256; ++i)
2117 png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
2121 #define PNG_GRAY_COLORMAP_ENTRIES 256
2124 make_ga_colormap(png_image_read_control *display)
2128 /* Alpha is retained, the output will be a color-map with entries
2129 * selected by six levels of alpha. One transparent entry, 6 gray
2130 * levels for all the intermediate alpha values, leaving 230 entries
2131 * for the opaque grays. The color-map entries are the six values
2132 * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
2135 * if (alpha > 229) // opaque
2137 * // The 231 entries are selected to make the math below work:
2139 * entry = (231 * gray + 128) >> 8;
2141 * else if (alpha < 26) // transparent
2146 * else // partially opaque
2148 * base = 226 + 6 * PNG_DIV51(alpha);
2149 * entry = PNG_DIV51(gray);
2155 unsigned int gray = (i * 256 + 115) / 231;
2156 png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2159 /* 255 is used here for the component values for consistency with the code
2160 * that undoes premultiplication in pngwrite.c.
2162 png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2169 png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2176 #define PNG_GA_COLORMAP_ENTRIES 256
2179 make_rgb_colormap(png_image_read_control *display)
2183 /* Build a 6x6x6 opaque RGB cube */
2184 for (i=r=0; r<6; ++r)
2193 png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2201 #define PNG_RGB_COLORMAP_ENTRIES 216
2203 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2204 #define PNG_RGB_INDEX(r,g,b) \
2205 ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2208 png_image_read_colormap(png_voidp argument)
2210 png_image_read_control *display =
2211 png_voidcast(png_image_read_control*, argument);
2212 png_imagep image = display->image;
2214 png_structrp png_ptr = image->opaque->png_ptr;
2215 png_uint_32 output_format = image->format;
2216 int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2219 unsigned int cmap_entries;
2220 unsigned int output_processing; /* Output processing option */
2221 unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2223 /* Background information; the background color and the index of this color
2224 * in the color-map if it exists (else 256).
2226 unsigned int background_index = 256;
2227 png_uint_32 back_r, back_g, back_b;
2229 /* Flags to accumulate things that need to be done to the input. */
2230 int expand_tRNS = 0;
2232 /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2233 * very difficult to do, the results look awful, and it is difficult to see
2234 * what possible use it is because the application can't control the
2237 if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2238 png_ptr->num_trans > 0) /* alpha in input */ &&
2239 ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2241 if (output_encoding == P_LINEAR) /* compose on black */
2242 back_b = back_g = back_r = 0;
2244 else if (display->background == NULL /* no way to remove it */)
2246 "background color must be supplied to remove alpha/transparency");
2248 /* Get a copy of the background color (this avoids repeating the checks
2249 * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the
2254 back_g = display->background->green;
2255 if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2257 back_r = display->background->red;
2258 back_b = display->background->blue;
2261 back_b = back_r = back_g;
2265 else if (output_encoding == P_LINEAR)
2266 back_b = back_r = back_g = 65535;
2269 back_b = back_r = back_g = 255;
2271 /* Default the input file gamma if required - this is necessary because
2272 * libpng assumes that if no gamma information is present the data is in the
2273 * output format, but the simplified API deduces the gamma from the input
2276 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2278 /* Do this directly, not using the png_colorspace functions, to ensure
2279 * that it happens even if the colorspace is invalid (though probably if
2280 * it is the setting will be ignored) Note that the same thing can be
2281 * achieved at the application interface with png_set_gAMA.
2283 if (png_ptr->bit_depth == 16 &&
2284 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2285 png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2288 png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2290 png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2293 /* Decide what to do based on the PNG color type of the input data. The
2294 * utility function png_create_colormap_entry deals with most aspects of the
2295 * output transformations; this code works out how to produce bytes of
2296 * color-map entries from the original format.
2298 switch (png_ptr->color_type)
2300 case PNG_COLOR_TYPE_GRAY:
2301 if (png_ptr->bit_depth <= 8)
2303 /* There at most 256 colors in the output, regardless of
2306 unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2308 cmap_entries = 1U << png_ptr->bit_depth;
2309 if (cmap_entries > image->colormap_entries)
2310 png_error(png_ptr, "gray[8] color-map: too few entries");
2312 step = 255 / (cmap_entries - 1);
2313 output_processing = PNG_CMAP_NONE;
2315 /* If there is a tRNS chunk then this either selects a transparent
2316 * value or, if the output has no alpha, the background color.
2318 if (png_ptr->num_trans > 0)
2320 trans = png_ptr->trans_color.gray;
2322 if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2323 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2326 /* png_create_colormap_entry just takes an RGBA and writes the
2327 * corresponding color-map entry using the format from 'image',
2328 * including the required conversion to sRGB or linear as
2329 * appropriate. The input values are always either sRGB (if the
2330 * gamma correction flag is 0) or 0..255 scaled file encoded values
2331 * (if the function must gamma correct them).
2333 for (i=val=0; i<cmap_entries; ++i, val += step)
2335 /* 'i' is a file value. While this will result in duplicated
2336 * entries for 8-bit non-sRGB encoded files it is necessary to
2337 * have non-gamma corrected values to do tRNS handling.
2340 png_create_colormap_entry(display, i, val, val, val, 255,
2341 P_FILE/*8-bit with file gamma*/);
2343 /* Else this entry is transparent. The colors don't matter if
2344 * there is an alpha channel (back_alpha == 0), but it does no
2345 * harm to pass them in; the values are not set above so this
2348 * NOTE: this preserves the full precision of the application
2349 * supplied background color when it is used.
2352 png_create_colormap_entry(display, i, back_r, back_g, back_b,
2353 back_alpha, output_encoding);
2356 /* We need libpng to preserve the original encoding. */
2357 data_encoding = P_FILE;
2359 /* The rows from libpng, while technically gray values, are now also
2360 * color-map indices; however, they may need to be expanded to 1
2361 * byte per pixel. This is what png_set_packing does (i.e., it
2362 * unpacks the bit values into bytes.)
2364 if (png_ptr->bit_depth < 8)
2365 png_set_packing(png_ptr);
2368 else /* bit depth is 16 */
2370 /* The 16-bit input values can be converted directly to 8-bit gamma
2371 * encoded values; however, if a tRNS chunk is present 257 color-map
2372 * entries are required. This means that the extra entry requires
2373 * special processing; add an alpha channel, sacrifice gray level
2374 * 254 and convert transparent (alpha==0) entries to that.
2376 * Use libpng to chop the data to 8 bits. Convert it to sRGB at the
2377 * same time to minimize quality loss. If a tRNS chunk is present
2378 * this means libpng must handle it too; otherwise it is impossible
2379 * to do the exact match on the 16-bit value.
2381 * If the output has no alpha channel *and* the background color is
2382 * gray then it is possible to let libpng handle the substitution by
2383 * ensuring that the corresponding gray level matches the background
2386 data_encoding = P_sRGB;
2388 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2389 png_error(png_ptr, "gray[16] color-map: too few entries");
2391 cmap_entries = (unsigned int)make_gray_colormap(display);
2393 if (png_ptr->num_trans > 0)
2395 unsigned int back_alpha;
2397 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2402 if (back_r == back_g && back_g == back_b)
2404 /* Background is gray; no special processing will be
2408 png_uint_32 gray = back_g;
2410 if (output_encoding == P_LINEAR)
2412 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2414 /* And make sure the corresponding palette entry
2417 png_create_colormap_entry(display, gray, back_g, back_g,
2418 back_g, 65535, P_LINEAR);
2421 /* The background passed to libpng, however, must be the
2424 c.index = 0; /*unused*/
2425 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2427 /* NOTE: does this work without expanding tRNS to alpha?
2428 * It should be the color->gray case below apparently
2431 png_set_background_fixed(png_ptr, &c,
2432 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2433 0/*gamma: not used*/);
2435 output_processing = PNG_CMAP_NONE;
2439 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2444 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2448 /* output_processing means that the libpng-processed row will be
2449 * 8-bit GA and it has to be processing to single byte color-map
2450 * values. Entry 254 is replaced by either a completely
2451 * transparent entry or by the background color at full
2452 * precision (and the background color is not a simple gray
2453 * level in this case.)
2456 output_processing = PNG_CMAP_TRANS;
2457 background_index = 254;
2459 /* And set (overwrite) color-map entry 254 to the actual
2460 * background color at full precision.
2462 png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2463 back_alpha, output_encoding);
2467 output_processing = PNG_CMAP_NONE;
2471 case PNG_COLOR_TYPE_GRAY_ALPHA:
2472 /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum
2473 * of 65536 combinations. If, however, the alpha channel is to be
2474 * removed there are only 256 possibilities if the background is gray.
2475 * (Otherwise there is a subset of the 65536 possibilities defined by
2476 * the triangle between black, white and the background color.)
2478 * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to
2479 * worry about tRNS matching - tRNS is ignored if there is an alpha
2482 data_encoding = P_sRGB;
2484 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2486 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2487 png_error(png_ptr, "gray+alpha color-map: too few entries");
2489 cmap_entries = (unsigned int)make_ga_colormap(display);
2491 background_index = PNG_CMAP_GA_BACKGROUND;
2492 output_processing = PNG_CMAP_GA;
2495 else /* alpha is removed */
2497 /* Alpha must be removed as the PNG data is processed when the
2498 * background is a color because the G and A channels are
2499 * independent and the vector addition (non-parallel vectors) is a
2502 * This can be reduced to the same algorithm as above by making a
2503 * colormap containing gray levels (for the opaque grays), a
2504 * background entry (for a transparent pixel) and a set of four six
2505 * level color values, one set for each intermediate alpha value.
2506 * See the comments in make_ga_colormap for how this works in the
2507 * per-pixel processing.
2509 * If the background is gray, however, we only need a 256 entry gray
2510 * level color map. It is sufficient to make the entry generated
2511 * for the background color be exactly the color specified.
2513 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2514 (back_r == back_g && back_g == back_b))
2516 /* Background is gray; no special processing will be required. */
2518 png_uint_32 gray = back_g;
2520 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2521 png_error(png_ptr, "gray-alpha color-map: too few entries");
2523 cmap_entries = (unsigned int)make_gray_colormap(display);
2525 if (output_encoding == P_LINEAR)
2527 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2529 /* And make sure the corresponding palette entry matches. */
2530 png_create_colormap_entry(display, gray, back_g, back_g,
2531 back_g, 65535, P_LINEAR);
2534 /* The background passed to libpng, however, must be the sRGB
2537 c.index = 0; /*unused*/
2538 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2540 png_set_background_fixed(png_ptr, &c,
2541 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2542 0/*gamma: not used*/);
2544 output_processing = PNG_CMAP_NONE;
2551 /* This is the same as png_make_ga_colormap, above, except that
2552 * the entries are all opaque.
2554 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2555 png_error(png_ptr, "ga-alpha color-map: too few entries");
2560 png_uint_32 gray = (i * 256 + 115) / 231;
2561 png_create_colormap_entry(display, i++, gray, gray, gray,
2565 /* NOTE: this preserves the full precision of the application
2568 background_index = i;
2569 png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2571 /* Coverity claims that output_encoding
2572 * cannot be 2 (P_LINEAR) here.
2575 output_encoding == P_LINEAR ? 65535U : 255U,
2579 /* For non-opaque input composite on the sRGB background - this
2580 * requires inverting the encoding for each component. The input
2581 * is still converted to the sRGB encoding because this is a
2582 * reasonable approximate to the logarithmic curve of human
2583 * visual sensitivity, at least over the narrow range which PNG
2584 * represents. Consequently 'G' is always sRGB encoded, while
2585 * 'A' is linear. We need the linear background colors.
2587 if (output_encoding == P_sRGB) /* else already linear */
2589 /* This may produce a value not exactly matching the
2590 * background, but that's ok because these numbers are only
2591 * used when alpha != 0
2593 back_r = png_sRGB_table[back_r];
2594 back_g = png_sRGB_table[back_g];
2595 back_b = png_sRGB_table[back_b];
2602 /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2603 * by an 8-bit alpha value (0..255).
2605 png_uint_32 alpha = 51 * a;
2606 png_uint_32 back_rx = (255-alpha) * back_r;
2607 png_uint_32 back_gx = (255-alpha) * back_g;
2608 png_uint_32 back_bx = (255-alpha) * back_b;
2612 png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2614 png_create_colormap_entry(display, i++,
2615 PNG_sRGB_FROM_LINEAR(gray + back_rx),
2616 PNG_sRGB_FROM_LINEAR(gray + back_gx),
2617 PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2622 output_processing = PNG_CMAP_GA;
2627 case PNG_COLOR_TYPE_RGB:
2628 case PNG_COLOR_TYPE_RGB_ALPHA:
2629 /* Exclude the case where the output is gray; we can always handle this
2630 * with the cases above.
2632 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2634 /* The color-map will be grayscale, so we may as well convert the
2635 * input RGB values to a simple grayscale and use the grayscale
2638 * NOTE: calling this apparently damages the recognition of the
2639 * transparent color in background color handling; call
2640 * png_set_tRNS_to_alpha before png_set_background_fixed.
2642 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2644 data_encoding = P_sRGB;
2646 /* The output will now be one or two 8-bit gray or gray+alpha
2647 * channels. The more complex case arises when the input has alpha.
2649 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2650 png_ptr->num_trans > 0) &&
2651 (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2653 /* Both input and output have an alpha channel, so no background
2654 * processing is required; just map the GA bytes to the right
2659 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2660 png_error(png_ptr, "rgb[ga] color-map: too few entries");
2662 cmap_entries = (unsigned int)make_ga_colormap(display);
2663 background_index = PNG_CMAP_GA_BACKGROUND;
2664 output_processing = PNG_CMAP_GA;
2669 /* Either the input or the output has no alpha channel, so there
2670 * will be no non-opaque pixels in the color-map; it will just be
2673 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2674 png_error(png_ptr, "rgb[gray] color-map: too few entries");
2676 /* Ideally this code would use libpng to do the gamma correction,
2677 * but if an input alpha channel is to be removed we will hit the
2678 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2679 * correction bug). Fix this by dropping the gamma correction in
2680 * this case and doing it in the palette; this will result in
2681 * duplicate palette entries, but that's better than the
2682 * alternative of double gamma correction.
2684 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2685 png_ptr->num_trans > 0) &&
2686 png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2688 cmap_entries = (unsigned int)make_gray_file_colormap(display);
2689 data_encoding = P_FILE;
2693 cmap_entries = (unsigned int)make_gray_colormap(display);
2695 /* But if the input has alpha or transparency it must be removed
2697 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2698 png_ptr->num_trans > 0)
2701 png_uint_32 gray = back_g;
2703 /* We need to ensure that the application background exists in
2704 * the colormap and that completely transparent pixels map to
2705 * it. Achieve this simply by ensuring that the entry
2706 * selected for the background really is the background color.
2708 if (data_encoding == P_FILE) /* from the fixup above */
2710 /* The app supplied a gray which is in output_encoding, we
2711 * need to convert it to a value of the input (P_FILE)
2712 * encoding then set this palette entry to the required
2715 if (output_encoding == P_sRGB)
2716 gray = png_sRGB_table[gray]; /* now P_LINEAR */
2718 gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2719 png_ptr->colorspace.gamma)); /* now P_FILE */
2721 /* And make sure the corresponding palette entry contains
2722 * exactly the required sRGB value.
2724 png_create_colormap_entry(display, gray, back_g, back_g,
2725 back_g, 0/*unused*/, output_encoding);
2728 else if (output_encoding == P_LINEAR)
2730 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2732 /* And make sure the corresponding palette entry matches.
2734 png_create_colormap_entry(display, gray, back_g, back_g,
2735 back_g, 0/*unused*/, P_LINEAR);
2738 /* The background passed to libpng, however, must be the
2739 * output (normally sRGB) value.
2741 c.index = 0; /*unused*/
2742 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2744 /* NOTE: the following is apparently a bug in libpng. Without
2745 * it the transparent color recognition in
2746 * png_set_background_fixed seems to go wrong.
2749 png_set_background_fixed(png_ptr, &c,
2750 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2751 0/*gamma: not used*/);
2754 output_processing = PNG_CMAP_NONE;
2758 else /* output is color */
2760 /* We could use png_quantize here so long as there is no transparent
2761 * color or alpha; png_quantize ignores alpha. Easier overall just
2762 * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2763 * Consequently we always want libpng to produce sRGB data.
2765 data_encoding = P_sRGB;
2767 /* Is there any transparency or alpha? */
2768 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2769 png_ptr->num_trans > 0)
2771 /* Is there alpha in the output too? If so all four channels are
2772 * processed into a special RGB cube with alpha support.
2774 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2778 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2779 png_error(png_ptr, "rgb+alpha color-map: too few entries");
2781 cmap_entries = (unsigned int)make_rgb_colormap(display);
2783 /* Add a transparent entry. */
2784 png_create_colormap_entry(display, cmap_entries, 255, 255,
2787 /* This is stored as the background index for the processing
2790 background_index = cmap_entries++;
2792 /* Add 27 r,g,b entries each with alpha 0.5. */
2793 for (r=0; r<256; r = (r << 1) | 0x7f)
2797 for (g=0; g<256; g = (g << 1) | 0x7f)
2801 /* This generates components with the values 0, 127 and
2804 for (b=0; b<256; b = (b << 1) | 0x7f)
2805 png_create_colormap_entry(display, cmap_entries++,
2806 r, g, b, 128, P_sRGB);
2811 output_processing = PNG_CMAP_RGB_ALPHA;
2816 /* Alpha/transparency must be removed. The background must
2817 * exist in the color map (achieved by setting adding it after
2818 * the 666 color-map). If the standard processing code will
2819 * pick up this entry automatically that's all that is
2820 * required; libpng can be called to do the background
2823 unsigned int sample_size =
2824 PNG_IMAGE_SAMPLE_SIZE(output_format);
2825 png_uint_32 r, g, b; /* sRGB background */
2827 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2828 png_error(png_ptr, "rgb-alpha color-map: too few entries");
2830 cmap_entries = (unsigned int)make_rgb_colormap(display);
2832 png_create_colormap_entry(display, cmap_entries, back_r,
2833 back_g, back_b, 0/*unused*/, output_encoding);
2835 if (output_encoding == P_LINEAR)
2837 r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2838 g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2839 b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2849 /* Compare the newly-created color-map entry with the one the
2850 * PNG_CMAP_RGB algorithm will use. If the two entries don't
2851 * match, add the new one and set this as the background
2854 if (memcmp((png_const_bytep)display->colormap +
2855 sample_size * cmap_entries,
2856 (png_const_bytep)display->colormap +
2857 sample_size * PNG_RGB_INDEX(r,g,b),
2860 /* The background color must be added. */
2861 background_index = cmap_entries++;
2863 /* Add 27 r,g,b entries each with created by composing with
2864 * the background at alpha 0.5.
2866 for (r=0; r<256; r = (r << 1) | 0x7f)
2868 for (g=0; g<256; g = (g << 1) | 0x7f)
2870 /* This generates components with the values 0, 127
2873 for (b=0; b<256; b = (b << 1) | 0x7f)
2874 png_create_colormap_entry(display, cmap_entries++,
2875 png_colormap_compose(display, r, P_sRGB, 128,
2876 back_r, output_encoding),
2877 png_colormap_compose(display, g, P_sRGB, 128,
2878 back_g, output_encoding),
2879 png_colormap_compose(display, b, P_sRGB, 128,
2880 back_b, output_encoding),
2881 0/*unused*/, output_encoding);
2886 output_processing = PNG_CMAP_RGB_ALPHA;
2889 else /* background color is in the standard color-map */
2893 c.index = 0; /*unused*/
2894 c.red = (png_uint_16)back_r;
2895 c.gray = c.green = (png_uint_16)back_g;
2896 c.blue = (png_uint_16)back_b;
2898 png_set_background_fixed(png_ptr, &c,
2899 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2900 0/*gamma: not used*/);
2902 output_processing = PNG_CMAP_RGB;
2907 else /* no alpha or transparency in the input */
2909 /* Alpha in the output is irrelevant, simply map the opaque input
2910 * pixels to the 6x6x6 color-map.
2912 if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2913 png_error(png_ptr, "rgb color-map: too few entries");
2915 cmap_entries = (unsigned int)make_rgb_colormap(display);
2916 output_processing = PNG_CMAP_RGB;
2921 case PNG_COLOR_TYPE_PALETTE:
2922 /* It's already got a color-map. It may be necessary to eliminate the
2923 * tRNS entries though.
2926 unsigned int num_trans = png_ptr->num_trans;
2927 png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2928 png_const_colorp colormap = png_ptr->palette;
2929 int do_background = trans != NULL &&
2930 (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2937 output_processing = PNG_CMAP_NONE;
2938 data_encoding = P_FILE; /* Don't change from color-map indices */
2939 cmap_entries = (unsigned int)png_ptr->num_palette;
2940 if (cmap_entries > 256)
2943 if (cmap_entries > (unsigned int)image->colormap_entries)
2944 png_error(png_ptr, "palette color-map: too few entries");
2946 for (i=0; i < cmap_entries; ++i)
2948 if (do_background != 0 && i < num_trans && trans[i] < 255)
2951 png_create_colormap_entry(display, i, back_r, back_g,
2952 back_b, 0, output_encoding);
2956 /* Must compose the PNG file color in the color-map entry
2957 * on the sRGB color in 'back'.
2959 png_create_colormap_entry(display, i,
2960 png_colormap_compose(display, colormap[i].red,
2961 P_FILE, trans[i], back_r, output_encoding),
2962 png_colormap_compose(display, colormap[i].green,
2963 P_FILE, trans[i], back_g, output_encoding),
2964 png_colormap_compose(display, colormap[i].blue,
2965 P_FILE, trans[i], back_b, output_encoding),
2966 output_encoding == P_LINEAR ? trans[i] * 257U :
2973 png_create_colormap_entry(display, i, colormap[i].red,
2974 colormap[i].green, colormap[i].blue,
2975 i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2978 /* The PNG data may have indices packed in fewer than 8 bits, it
2979 * must be expanded if so.
2981 if (png_ptr->bit_depth < 8)
2982 png_set_packing(png_ptr);
2987 png_error(png_ptr, "invalid PNG color type");
2991 /* Now deal with the output processing */
2992 if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2993 (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
2994 png_set_tRNS_to_alpha(png_ptr);
2996 switch (data_encoding)
2999 /* Change to 8-bit sRGB */
3000 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
3004 if (png_ptr->bit_depth > 8)
3005 png_set_scale_16(png_ptr);
3010 png_error(png_ptr, "bad data option (internal error)");
3014 if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
3015 png_error(png_ptr, "color map overflow (BAD internal error)");
3017 image->colormap_entries = cmap_entries;
3019 /* Double check using the recorded background index */
3020 switch (output_processing)
3023 if (background_index != PNG_CMAP_NONE_BACKGROUND)
3024 goto bad_background;
3028 if (background_index != PNG_CMAP_GA_BACKGROUND)
3029 goto bad_background;
3032 case PNG_CMAP_TRANS:
3033 if (background_index >= cmap_entries ||
3034 background_index != PNG_CMAP_TRANS_BACKGROUND)
3035 goto bad_background;
3039 if (background_index != PNG_CMAP_RGB_BACKGROUND)
3040 goto bad_background;
3043 case PNG_CMAP_RGB_ALPHA:
3044 if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
3045 goto bad_background;
3049 png_error(png_ptr, "bad processing option (internal error)");
3052 png_error(png_ptr, "bad background index (internal error)");
3055 display->colormap_processing = (int)output_processing;
3060 /* The final part of the color-map read called from png_image_finish_read. */
3062 png_image_read_and_map(png_voidp argument)
3064 png_image_read_control *display = png_voidcast(png_image_read_control*,
3066 png_imagep image = display->image;
3067 png_structrp png_ptr = image->opaque->png_ptr;
3070 /* Called when the libpng data must be transformed into the color-mapped
3071 * form. There is a local row buffer in display->local and this routine must
3072 * do the interlace handling.
3074 switch (png_ptr->interlaced)
3076 case PNG_INTERLACE_NONE:
3080 case PNG_INTERLACE_ADAM7:
3081 passes = PNG_INTERLACE_ADAM7_PASSES;
3085 png_error(png_ptr, "unknown interlace type");
3089 png_uint_32 height = image->height;
3090 png_uint_32 width = image->width;
3091 int proc = display->colormap_processing;
3092 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3093 ptrdiff_t step_row = display->row_bytes;
3096 for (pass = 0; pass < passes; ++pass)
3098 unsigned int startx, stepx, stepy;
3101 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3103 /* The row may be empty for a short image: */
3104 if (PNG_PASS_COLS(width, pass) == 0)
3107 startx = PNG_PASS_START_COL(pass);
3108 stepx = PNG_PASS_COL_OFFSET(pass);
3109 y = PNG_PASS_START_ROW(pass);
3110 stepy = PNG_PASS_ROW_OFFSET(pass);
3120 for (; y<height; y += stepy)
3122 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3123 png_bytep outrow = first_row + y * step_row;
3124 png_const_bytep end_row = outrow + width;
3126 /* Read read the libpng data into the temporary buffer. */
3127 png_read_row(png_ptr, inrow, NULL);
3129 /* Now process the row according to the processing option, note
3130 * that the caller verifies that the format of the libpng output
3131 * data is as required.
3137 for (; outrow < end_row; outrow += stepx)
3139 /* The data is always in the PNG order */
3140 unsigned int gray = *inrow++;
3141 unsigned int alpha = *inrow++;
3144 /* NOTE: this code is copied as a comment in
3145 * make_ga_colormap above. Please update the
3146 * comment if you change this code!
3148 if (alpha > 229) /* opaque */
3150 entry = (231 * gray + 128) >> 8;
3152 else if (alpha < 26) /* transparent */
3156 else /* partially opaque */
3158 entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3161 *outrow = (png_byte)entry;
3165 case PNG_CMAP_TRANS:
3166 for (; outrow < end_row; outrow += stepx)
3168 png_byte gray = *inrow++;
3169 png_byte alpha = *inrow++;
3172 *outrow = PNG_CMAP_TRANS_BACKGROUND;
3174 else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3178 *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3183 for (; outrow < end_row; outrow += stepx)
3185 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3190 case PNG_CMAP_RGB_ALPHA:
3191 for (; outrow < end_row; outrow += stepx)
3193 unsigned int alpha = inrow[3];
3195 /* Because the alpha entries only hold alpha==0.5 values
3196 * split the processing at alpha==0.25 (64) and 0.75
3201 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3204 else if (alpha < 64)
3205 *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3209 /* Likewise there are three entries for each of r, g
3210 * and b. We could select the entry by popcount on
3211 * the top two bits on those architectures that
3212 * support it, this is what the code below does,
3215 unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3217 /* Here are how the values map:
3223 * So, as above with the explicit alpha checks, the
3224 * breakpoints are at 64 and 196.
3226 if (inrow[0] & 0x80) back_i += 9; /* red */
3227 if (inrow[0] & 0x40) back_i += 9;
3228 if (inrow[0] & 0x80) back_i += 3; /* green */
3229 if (inrow[0] & 0x40) back_i += 3;
3230 if (inrow[0] & 0x80) back_i += 1; /* blue */
3231 if (inrow[0] & 0x40) back_i += 1;
3233 *outrow = (png_byte)back_i;
3251 png_image_read_colormapped(png_voidp argument)
3253 png_image_read_control *display = png_voidcast(png_image_read_control*,
3255 png_imagep image = display->image;
3256 png_controlp control = image->opaque;
3257 png_structrp png_ptr = control->png_ptr;
3258 png_inforp info_ptr = control->info_ptr;
3260 int passes = 0; /* As a flag */
3262 PNG_SKIP_CHUNKS(png_ptr);
3264 /* Update the 'info' structure and make sure the result is as required; first
3265 * make sure to turn on the interlace handling if it will be required
3266 * (because it can't be turned on *after* the call to png_read_update_info!)
3268 if (display->colormap_processing == PNG_CMAP_NONE)
3269 passes = png_set_interlace_handling(png_ptr);
3271 png_read_update_info(png_ptr, info_ptr);
3273 /* The expected output can be deduced from the colormap_processing option. */
3274 switch (display->colormap_processing)
3277 /* Output must be one channel and one byte per pixel, the output
3278 * encoding can be anything.
3280 if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3281 info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3282 info_ptr->bit_depth == 8)
3287 case PNG_CMAP_TRANS:
3289 /* Output must be two channels and the 'G' one must be sRGB, the latter
3290 * can be checked with an exact number because it should have been set
3291 * to this number above!
3293 if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3294 info_ptr->bit_depth == 8 &&
3295 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3296 image->colormap_entries == 256)
3302 /* Output must be 8-bit sRGB encoded RGB */
3303 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3304 info_ptr->bit_depth == 8 &&
3305 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3306 image->colormap_entries == 216)
3311 case PNG_CMAP_RGB_ALPHA:
3312 /* Output must be 8-bit sRGB encoded RGBA */
3313 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3314 info_ptr->bit_depth == 8 &&
3315 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3316 image->colormap_entries == 244 /* 216 + 1 + 27 */)
3323 png_error(png_ptr, "bad color-map processing (internal error)");
3326 /* Now read the rows. Do this here if it is possible to read directly into
3327 * the output buffer, otherwise allocate a local row buffer of the maximum
3328 * size libpng requires and call the relevant processing routine safely.
3331 png_voidp first_row = display->buffer;
3332 ptrdiff_t row_bytes = display->row_stride;
3334 /* The following expression is designed to work correctly whether it gives
3335 * a signed or an unsigned result.
3339 char *ptr = png_voidcast(char*, first_row);
3340 ptr += (image->height-1) * (-row_bytes);
3341 first_row = png_voidcast(png_voidp, ptr);
3344 display->first_row = first_row;
3345 display->row_bytes = row_bytes;
3351 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3353 display->local_row = row;
3354 result = png_safe_execute(image, png_image_read_and_map, display);
3355 display->local_row = NULL;
3356 png_free(png_ptr, row);
3363 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3365 while (--passes >= 0)
3367 png_uint_32 y = image->height;
3368 png_bytep row = png_voidcast(png_bytep, display->first_row);
3372 png_read_row(png_ptr, row, NULL);
3381 /* Just the row reading part of png_image_read. */
3383 png_image_read_composite(png_voidp argument)
3385 png_image_read_control *display = png_voidcast(png_image_read_control*,
3387 png_imagep image = display->image;
3388 png_structrp png_ptr = image->opaque->png_ptr;
3391 switch (png_ptr->interlaced)
3393 case PNG_INTERLACE_NONE:
3397 case PNG_INTERLACE_ADAM7:
3398 passes = PNG_INTERLACE_ADAM7_PASSES;
3402 png_error(png_ptr, "unknown interlace type");
3406 png_uint_32 height = image->height;
3407 png_uint_32 width = image->width;
3408 ptrdiff_t step_row = display->row_bytes;
3409 unsigned int channels =
3410 (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3413 for (pass = 0; pass < passes; ++pass)
3415 unsigned int startx, stepx, stepy;
3418 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3420 /* The row may be empty for a short image: */
3421 if (PNG_PASS_COLS(width, pass) == 0)
3424 startx = PNG_PASS_START_COL(pass) * channels;
3425 stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3426 y = PNG_PASS_START_ROW(pass);
3427 stepy = PNG_PASS_ROW_OFFSET(pass);
3438 for (; y<height; y += stepy)
3440 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3442 png_const_bytep end_row;
3444 /* Read the row, which is packed: */
3445 png_read_row(png_ptr, inrow, NULL);
3447 outrow = png_voidcast(png_bytep, display->first_row);
3448 outrow += y * step_row;
3449 end_row = outrow + width * channels;
3451 /* Now do the composition on each pixel in this row. */
3453 for (; outrow < end_row; outrow += stepx)
3455 png_byte alpha = inrow[channels];
3457 if (alpha > 0) /* else no change to the output */
3461 for (c=0; c<channels; ++c)
3463 png_uint_32 component = inrow[c];
3465 if (alpha < 255) /* else just use component */
3467 /* This is PNG_OPTIMIZED_ALPHA, the component value
3468 * is a linear 8-bit value. Combine this with the
3469 * current outrow[c] value which is sRGB encoded.
3470 * Arithmetic here is 16-bits to preserve the output
3473 component *= 257*255; /* =65535 */
3474 component += (255-alpha)*png_sRGB_table[outrow[c]];
3476 /* So 'component' is scaled by 255*65535 and is
3477 * therefore appropriate for the sRGB to linear
3480 component = PNG_sRGB_FROM_LINEAR(component);
3483 outrow[c] = (png_byte)component;
3487 inrow += channels+1; /* components and alpha channel */
3496 /* The do_local_background case; called when all the following transforms are to
3503 * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3504 * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3505 * correction. The fix-up is to prevent the PNG_COMPOSITE operation from
3506 * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3507 * row and handles the removal or pre-multiplication of the alpha channel.
3510 png_image_read_background(png_voidp argument)
3512 png_image_read_control *display = png_voidcast(png_image_read_control*,
3514 png_imagep image = display->image;
3515 png_structrp png_ptr = image->opaque->png_ptr;
3516 png_inforp info_ptr = image->opaque->info_ptr;
3517 png_uint_32 height = image->height;
3518 png_uint_32 width = image->width;
3521 /* Double check the convoluted logic below. We expect to get here with
3522 * libpng doing rgb to gray and gamma correction but background processing
3523 * left to the png_image_read_background function. The rows libpng produce
3524 * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3526 if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3527 png_error(png_ptr, "lost rgb to gray");
3529 if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3530 png_error(png_ptr, "unexpected compose");
3532 if (png_get_channels(png_ptr, info_ptr) != 2)
3533 png_error(png_ptr, "lost/gained channels");
3535 /* Expect the 8-bit case to always remove the alpha channel */
3536 if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3537 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3538 png_error(png_ptr, "unexpected 8-bit transformation");
3540 switch (png_ptr->interlaced)
3542 case PNG_INTERLACE_NONE:
3546 case PNG_INTERLACE_ADAM7:
3547 passes = PNG_INTERLACE_ADAM7_PASSES;
3551 png_error(png_ptr, "unknown interlace type");
3554 /* Use direct access to info_ptr here because otherwise the simplified API
3555 * would require PNG_EASY_ACCESS_SUPPORTED (just for this.) Note this is
3556 * checking the value after libpng expansions, not the original value in the
3559 switch (info_ptr->bit_depth)
3562 /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3563 * to be removed by composing on a background: either the row if
3564 * display->background is NULL or display->background->green if not.
3565 * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3568 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3569 ptrdiff_t step_row = display->row_bytes;
3571 for (pass = 0; pass < passes; ++pass)
3573 png_bytep row = png_voidcast(png_bytep, display->first_row);
3574 unsigned int startx, stepx, stepy;
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);
3584 stepx = PNG_PASS_COL_OFFSET(pass);
3585 y = PNG_PASS_START_ROW(pass);
3586 stepy = PNG_PASS_ROW_OFFSET(pass);
3596 if (display->background == NULL)
3598 for (; y<height; y += stepy)
3600 png_bytep inrow = png_voidcast(png_bytep,
3601 display->local_row);
3602 png_bytep outrow = first_row + y * step_row;
3603 png_const_bytep end_row = outrow + width;
3605 /* Read the row, which is packed: */
3606 png_read_row(png_ptr, inrow, NULL);
3608 /* Now do the composition on each pixel in this row. */
3610 for (; outrow < end_row; outrow += stepx)
3612 png_byte alpha = inrow[1];
3614 if (alpha > 0) /* else no change to the output */
3616 png_uint_32 component = inrow[0];
3618 if (alpha < 255) /* else just use component */
3620 /* Since PNG_OPTIMIZED_ALPHA was not set it is
3621 * necessary to invert the sRGB transfer
3622 * function and multiply the alpha out.
3624 component = png_sRGB_table[component] * alpha;
3625 component += png_sRGB_table[outrow[0]] *
3627 component = PNG_sRGB_FROM_LINEAR(component);
3630 outrow[0] = (png_byte)component;
3633 inrow += 2; /* gray and alpha channel */
3638 else /* constant background value */
3640 png_byte background8 = display->background->green;
3641 png_uint_16 background = png_sRGB_table[background8];
3643 for (; y<height; y += stepy)
3645 png_bytep inrow = png_voidcast(png_bytep,
3646 display->local_row);
3647 png_bytep outrow = first_row + y * step_row;
3648 png_const_bytep end_row = outrow + width;
3650 /* Read the row, which is packed: */
3651 png_read_row(png_ptr, inrow, NULL);
3653 /* Now do the composition on each pixel in this row. */
3655 for (; outrow < end_row; outrow += stepx)
3657 png_byte alpha = inrow[1];
3659 if (alpha > 0) /* else use background */
3661 png_uint_32 component = inrow[0];
3663 if (alpha < 255) /* else just use component */
3665 component = png_sRGB_table[component] * alpha;
3666 component += background * (255-alpha);
3667 component = PNG_sRGB_FROM_LINEAR(component);
3670 outrow[0] = (png_byte)component;
3674 outrow[0] = background8;
3676 inrow += 2; /* gray and alpha channel */
3679 row += display->row_bytes;
3687 /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3688 * still be done and, maybe, the alpha channel removed. This code also
3689 * handles the alpha-first option.
3692 png_uint_16p first_row = png_voidcast(png_uint_16p,
3693 display->first_row);
3694 /* The division by two is safe because the caller passed in a
3695 * stride which was multiplied by 2 (below) to get row_bytes.
3697 ptrdiff_t step_row = display->row_bytes / 2;
3698 unsigned int preserve_alpha = (image->format &
3699 PNG_FORMAT_FLAG_ALPHA) != 0;
3700 unsigned int outchannels = 1U+preserve_alpha;
3703 # ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3704 if (preserve_alpha != 0 &&
3705 (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3709 for (pass = 0; pass < passes; ++pass)
3711 unsigned int startx, stepx, stepy;
3714 /* The 'x' start and step are adjusted to output components here.
3716 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3718 /* The row may be empty for a short image: */
3719 if (PNG_PASS_COLS(width, pass) == 0)
3722 startx = PNG_PASS_START_COL(pass) * outchannels;
3723 stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3724 y = PNG_PASS_START_ROW(pass);
3725 stepy = PNG_PASS_ROW_OFFSET(pass);
3732 stepx = outchannels;
3736 for (; y<height; y += stepy)
3738 png_const_uint_16p inrow;
3739 png_uint_16p outrow = first_row + y*step_row;
3740 png_uint_16p end_row = outrow + width * outchannels;
3742 /* Read the row, which is packed: */
3743 png_read_row(png_ptr, png_voidcast(png_bytep,
3744 display->local_row), NULL);
3745 inrow = png_voidcast(png_const_uint_16p, display->local_row);
3747 /* Now do the pre-multiplication on each pixel in this row.
3750 for (; outrow < end_row; outrow += stepx)
3752 png_uint_32 component = inrow[0];
3753 png_uint_16 alpha = inrow[1];
3755 if (alpha > 0) /* else 0 */
3757 if (alpha < 65535) /* else just use component */
3768 outrow[swap_alpha] = (png_uint_16)component;
3769 if (preserve_alpha != 0)
3770 outrow[1 ^ swap_alpha] = alpha;
3772 inrow += 2; /* components and alpha channel */
3781 png_error(png_ptr, "unexpected bit depth");
3788 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3790 png_image_read_direct(png_voidp argument)
3792 png_image_read_control *display = png_voidcast(png_image_read_control*,
3794 png_imagep image = display->image;
3795 png_structrp png_ptr = image->opaque->png_ptr;
3796 png_inforp info_ptr = image->opaque->info_ptr;
3798 png_uint_32 format = image->format;
3799 int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3800 int do_local_compose = 0;
3801 int do_local_background = 0; /* to avoid double gamma correction bug */
3804 /* Add transforms to ensure the correct output format is produced then check
3805 * that the required implementation support is there. Always expand; always
3806 * need 8 bits minimum, no palette and expanded tRNS.
3808 png_set_expand(png_ptr);
3810 /* Now check the format to see if it was modified. */
3812 png_uint_32 base_format = png_image_format(png_ptr) &
3813 ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3814 png_uint_32 change = format ^ base_format;
3815 png_fixed_point output_gamma;
3816 int mode; /* alpha mode */
3818 /* Do this first so that we have a record if rgb to gray is happening. */
3819 if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3821 /* gray<->color transformation required. */
3822 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3823 png_set_gray_to_rgb(png_ptr);
3827 /* libpng can't do both rgb to gray and
3828 * background/pre-multiplication if there is also significant gamma
3829 * correction, because both operations require linear colors and
3830 * the code only supports one transform doing the gamma correction.
3831 * Handle this by doing the pre-multiplication or background
3832 * operation in this code, if necessary.
3834 * TODO: fix this by rewriting pngrtran.c (!)
3836 * For the moment (given that fixing this in pngrtran.c is an
3837 * enormous change) 'do_local_background' is used to indicate that
3838 * the problem exists.
3840 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3841 do_local_background = 1/*maybe*/;
3843 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3844 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3847 change &= ~PNG_FORMAT_FLAG_COLOR;
3850 /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3853 png_fixed_point input_gamma_default;
3855 if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3856 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3857 input_gamma_default = PNG_GAMMA_LINEAR;
3859 input_gamma_default = PNG_DEFAULT_sRGB;
3861 /* Call png_set_alpha_mode to set the default for the input gamma; the
3862 * output gamma is set by a second call below.
3864 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3869 /* If there *is* an alpha channel in the input it must be multiplied
3870 * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3872 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3873 mode = PNG_ALPHA_STANDARD; /* associated alpha */
3876 mode = PNG_ALPHA_PNG;
3878 output_gamma = PNG_GAMMA_LINEAR;
3883 mode = PNG_ALPHA_PNG;
3884 output_gamma = PNG_DEFAULT_sRGB;
3887 if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
3889 mode = PNG_ALPHA_OPTIMIZED;
3890 change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3893 /* If 'do_local_background' is set check for the presence of gamma
3894 * correction; this is part of the work-round for the libpng bug
3897 * TODO: fix libpng and remove this.
3899 if (do_local_background != 0)
3901 png_fixed_point gtest;
3903 /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3904 * gamma correction, the screen gamma hasn't been set on png_struct
3905 * yet; it's set below. png_struct::gamma, however, is set to the
3908 if (png_muldiv(>est, output_gamma, png_ptr->colorspace.gamma,
3909 PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
3910 do_local_background = 0;
3912 else if (mode == PNG_ALPHA_STANDARD)
3914 do_local_background = 2/*required*/;
3915 mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3918 /* else leave as 1 for the checks below */
3921 /* If the bit-depth changes then handle that here. */
3922 if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3924 if (linear != 0 /*16-bit output*/)
3925 png_set_expand_16(png_ptr);
3927 else /* 8-bit output */
3928 png_set_scale_16(png_ptr);
3930 change &= ~PNG_FORMAT_FLAG_LINEAR;
3933 /* Now the background/alpha channel changes. */
3934 if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3936 /* Removing an alpha channel requires composition for the 8-bit
3937 * formats; for the 16-bit it is already done, above, by the
3938 * pre-multiplication and the channel just needs to be stripped.
3940 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3942 /* If RGB->gray is happening the alpha channel must be left and the
3943 * operation completed locally.
3945 * TODO: fix libpng and remove this.
3947 if (do_local_background != 0)
3948 do_local_background = 2/*required*/;
3950 /* 16-bit output: just remove the channel */
3951 else if (linear != 0) /* compose on black (well, pre-multiply) */
3952 png_set_strip_alpha(png_ptr);
3954 /* 8-bit output: do an appropriate compose */
3955 else if (display->background != NULL)
3959 c.index = 0; /*unused*/
3960 c.red = display->background->red;
3961 c.green = display->background->green;
3962 c.blue = display->background->blue;
3963 c.gray = display->background->green;
3965 /* This is always an 8-bit sRGB value, using the 'green' channel
3966 * for gray is much better than calculating the luminance here;
3967 * we can get off-by-one errors in that calculation relative to
3968 * the app expectations and that will show up in transparent
3971 png_set_background_fixed(png_ptr, &c,
3972 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3973 0/*gamma: not used*/);
3976 else /* compose on row: implemented below. */
3978 do_local_compose = 1;
3979 /* This leaves the alpha channel in the output, so it has to be
3980 * removed by the code below. Set the encoding to the 'OPTIMIZE'
3981 * one so the code only has to hack on the pixels that require
3984 mode = PNG_ALPHA_OPTIMIZED;
3988 else /* output needs an alpha channel */
3990 /* This is tricky because it happens before the swap operation has
3991 * been accomplished; however, the swap does *not* swap the added
3992 * alpha channel (weird API), so it must be added in the correct
3995 png_uint_32 filler; /* opaque filler */
4004 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4005 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4007 where = PNG_FILLER_BEFORE;
4008 change &= ~PNG_FORMAT_FLAG_AFIRST;
4013 where = PNG_FILLER_AFTER;
4015 png_set_add_alpha(png_ptr, filler, where);
4018 /* This stops the (irrelevant) call to swap_alpha below. */
4019 change &= ~PNG_FORMAT_FLAG_ALPHA;
4022 /* Now set the alpha mode correctly; this is always done, even if there is
4023 * no alpha channel in either the input or the output because it correctly
4024 * sets the output gamma.
4026 png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
4028 # ifdef PNG_FORMAT_BGR_SUPPORTED
4029 if ((change & PNG_FORMAT_FLAG_BGR) != 0)
4031 /* Check only the output format; PNG is never BGR; don't do this if
4032 * the output is gray, but fix up the 'format' value in that case.
4034 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
4035 png_set_bgr(png_ptr);
4038 format &= ~PNG_FORMAT_FLAG_BGR;
4040 change &= ~PNG_FORMAT_FLAG_BGR;
4044 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
4045 if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
4047 /* Only relevant if there is an alpha channel - it's particularly
4048 * important to handle this correctly because do_local_compose may
4049 * be set above and then libpng will keep the alpha channel for this
4052 if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
4054 /* Disable this if doing a local background,
4055 * TODO: remove this when local background is no longer required.
4057 if (do_local_background != 2)
4058 png_set_swap_alpha(png_ptr);
4062 format &= ~PNG_FORMAT_FLAG_AFIRST;
4064 change &= ~PNG_FORMAT_FLAG_AFIRST;
4068 /* If the *output* is 16-bit then we need to check for a byte-swap on this
4073 png_uint_16 le = 0x0001;
4075 if ((*(png_const_bytep) & le) != 0)
4076 png_set_swap(png_ptr);
4079 /* If change is not now 0 some transformation is missing - error out. */
4081 png_error(png_ptr, "png_read_image: unsupported transformation");
4084 PNG_SKIP_CHUNKS(png_ptr);
4086 /* Update the 'info' structure and make sure the result is as required; first
4087 * make sure to turn on the interlace handling if it will be required
4088 * (because it can't be turned on *after* the call to png_read_update_info!)
4090 * TODO: remove the do_local_background fixup below.
4092 if (do_local_compose == 0 && do_local_background != 2)
4093 passes = png_set_interlace_handling(png_ptr);
4095 png_read_update_info(png_ptr, info_ptr);
4098 png_uint_32 info_format = 0;
4100 if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
4101 info_format |= PNG_FORMAT_FLAG_COLOR;
4103 if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
4105 /* do_local_compose removes this channel below. */
4106 if (do_local_compose == 0)
4108 /* do_local_background does the same if required. */
4109 if (do_local_background != 2 ||
4110 (format & PNG_FORMAT_FLAG_ALPHA) != 0)
4111 info_format |= PNG_FORMAT_FLAG_ALPHA;
4115 else if (do_local_compose != 0) /* internal error */
4116 png_error(png_ptr, "png_image_read: alpha channel lost");
4118 if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
4119 info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
4122 if (info_ptr->bit_depth == 16)
4123 info_format |= PNG_FORMAT_FLAG_LINEAR;
4125 #ifdef PNG_FORMAT_BGR_SUPPORTED
4126 if ((png_ptr->transformations & PNG_BGR) != 0)
4127 info_format |= PNG_FORMAT_FLAG_BGR;
4130 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4131 if (do_local_background == 2)
4133 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4134 info_format |= PNG_FORMAT_FLAG_AFIRST;
4137 if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
4138 ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
4139 (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
4141 if (do_local_background == 2)
4142 png_error(png_ptr, "unexpected alpha swap transformation");
4144 info_format |= PNG_FORMAT_FLAG_AFIRST;
4148 /* This is actually an internal error. */
4149 if (info_format != format)
4150 png_error(png_ptr, "png_read_image: invalid transformations");
4153 /* Now read the rows. If do_local_compose is set then it is necessary to use
4154 * a local row buffer. The output will be GA, RGBA or BGRA and must be
4155 * converted to G, RGB or BGR as appropriate. The 'local_row' member of the
4156 * display acts as a flag.
4159 png_voidp first_row = display->buffer;
4160 ptrdiff_t row_bytes = display->row_stride;
4165 /* The following expression is designed to work correctly whether it gives
4166 * a signed or an unsigned result.
4170 char *ptr = png_voidcast(char*, first_row);
4171 ptr += (image->height-1) * (-row_bytes);
4172 first_row = png_voidcast(png_voidp, ptr);
4175 display->first_row = first_row;
4176 display->row_bytes = row_bytes;
4179 if (do_local_compose != 0)
4182 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4184 display->local_row = row;
4185 result = png_safe_execute(image, png_image_read_composite, display);
4186 display->local_row = NULL;
4187 png_free(png_ptr, row);
4192 else if (do_local_background == 2)
4195 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4197 display->local_row = row;
4198 result = png_safe_execute(image, png_image_read_background, display);
4199 display->local_row = NULL;
4200 png_free(png_ptr, row);
4207 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4209 while (--passes >= 0)
4211 png_uint_32 y = image->height;
4212 png_bytep row = png_voidcast(png_bytep, display->first_row);
4216 png_read_row(png_ptr, row, NULL);
4226 png_image_finish_read(png_imagep image, png_const_colorp background,
4227 void *buffer, png_int_32 row_stride, void *colormap)
4229 if (image != NULL && image->version == PNG_IMAGE_VERSION)
4231 /* Check for row_stride overflow. This check is not performed on the
4232 * original PNG format because it may not occur in the output PNG format
4233 * and libpng deals with the issues of reading the original.
4235 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4237 /* The following checks just the 'row_stride' calculation to ensure it
4238 * fits in a signed 32-bit value. Because channels/components can be
4239 * either 1 or 2 bytes in size the length of a row can still overflow 32
4240 * bits; this is just to verify that the 'row_stride' argument can be
4243 if (image->width <= 0x7fffffffU/channels) /* no overflow */
4246 png_uint_32 png_row_stride = image->width * channels;
4248 if (row_stride == 0)
4249 row_stride = (png_int_32)/*SAFE*/png_row_stride;
4252 check = (png_uint_32)(-row_stride);
4255 check = (png_uint_32)row_stride;
4257 /* This verifies 'check', the absolute value of the actual stride
4258 * passed in and detects overflow in the application calculation (i.e.
4259 * if the app did actually pass in a non-zero 'row_stride'.
4261 if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4263 /* Now check for overflow of the image buffer calculation; this
4264 * limits the whole image size to 32 bits for API compatibility with
4265 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4267 * The PNG_IMAGE_BUFFER_SIZE macro is:
4269 * (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4271 * And the component size is always 1 or 2, so make sure that the
4272 * number of *bytes* that the application is saying are available
4273 * does actually fit into a 32-bit number.
4275 * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4276 * will be changed to use png_alloc_size_t; bigger images can be
4277 * accommodated on 64-bit systems.
4279 if (image->height <=
4280 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4282 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4283 (image->colormap_entries > 0 && colormap != NULL))
4286 png_image_read_control display;
4288 memset(&display, 0, (sizeof display));
4289 display.image = image;
4290 display.buffer = buffer;
4291 display.row_stride = row_stride;
4292 display.colormap = colormap;
4293 display.background = background;
4294 display.local_row = NULL;
4296 /* Choose the correct 'end' routine; for the color-map case
4297 * all the setup has already been done.
4299 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4301 png_safe_execute(image,
4302 png_image_read_colormap, &display) &&
4303 png_safe_execute(image,
4304 png_image_read_colormapped, &display);
4308 png_safe_execute(image,
4309 png_image_read_direct, &display);
4311 png_image_free(image);
4316 return png_image_error(image,
4317 "png_image_finish_read[color-map]: no color-map");
4321 return png_image_error(image,
4322 "png_image_finish_read: image too large");
4326 return png_image_error(image,
4327 "png_image_finish_read: invalid argument");
4331 return png_image_error(image,
4332 "png_image_finish_read: row_stride too large");
4335 else if (image != NULL)
4336 return png_image_error(image,
4337 "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4342 #endif /* SIMPLIFIED_READ */