2 /* pngread.c - read a PNG file
4 * Copyright (c) 2018-2019 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);
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 /* __TIZEN__ */
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 #if defined(PNG_READ_EXPAND_SUPPORTED) && \
1122 defined(PNG_ARM_NEON_IMPLEMENTATION)
1123 png_free(png_ptr, png_ptr->riffled_palette);
1124 png_ptr->riffled_palette = NULL;
1127 /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error
1128 * callbacks are still set at this point. They are required to complete the
1129 * destruction of the png_struct itself.
1133 /* Free all memory used by the read */
1135 png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
1136 png_infopp end_info_ptr_ptr)
1138 png_structrp png_ptr = NULL;
1140 png_debug(1, "in png_destroy_read_struct");
1142 if (png_ptr_ptr != NULL)
1143 png_ptr = *png_ptr_ptr;
1145 if (png_ptr == NULL)
1148 /* libpng 1.6.0: use the API to destroy info structs to ensure consistent
1149 * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API.
1150 * The extra was, apparently, unnecessary yet this hides memory leak bugs.
1152 png_destroy_info_struct(png_ptr, end_info_ptr_ptr);
1153 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1155 *png_ptr_ptr = NULL;
1156 png_read_destroy(png_ptr);
1157 png_destroy_png_struct(png_ptr);
1161 png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn)
1163 if (png_ptr == NULL)
1166 png_ptr->read_row_fn = read_row_fn;
1170 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
1171 #ifdef PNG_INFO_IMAGE_SUPPORTED
1173 png_read_png(png_structrp png_ptr, png_inforp info_ptr,
1174 int transforms, voidp params)
1176 if (png_ptr == NULL || info_ptr == NULL)
1179 /* png_read_info() gives us all of the information from the
1180 * PNG file before the first IDAT (image data chunk).
1182 png_read_info(png_ptr, info_ptr);
1183 if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep)))
1184 png_error(png_ptr, "Image is too high to process with png_read_png()");
1186 /* -------------- image transformations start here ------------------- */
1187 /* libpng 1.6.10: add code to cause a png_app_error if a selected TRANSFORM
1188 * is not implemented. This will only happen in de-configured (non-default)
1189 * libpng builds. The results can be unexpected - png_read_png may return
1190 * short or mal-formed rows because the transform is skipped.
1193 /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
1195 if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
1196 /* Added at libpng-1.5.4. "strip_16" produces the same result that it
1197 * did in earlier versions, while "scale_16" is now more accurate.
1199 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1200 png_set_scale_16(png_ptr);
1202 png_app_error(png_ptr, "PNG_TRANSFORM_SCALE_16 not supported");
1205 /* If both SCALE and STRIP are required pngrtran will effectively cancel the
1206 * latter by doing SCALE first. This is ok and allows apps not to check for
1207 * which is supported to get the right answer.
1209 if ((transforms & PNG_TRANSFORM_STRIP_16) != 0)
1210 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
1211 png_set_strip_16(png_ptr);
1213 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_16 not supported");
1216 /* Strip alpha bytes from the input data without combining with
1217 * the background (not recommended).
1219 if ((transforms & PNG_TRANSFORM_STRIP_ALPHA) != 0)
1220 #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1221 png_set_strip_alpha(png_ptr);
1223 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_ALPHA not supported");
1226 /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
1227 * byte into separate bytes (useful for paletted and grayscale images).
1229 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1230 #ifdef PNG_READ_PACK_SUPPORTED
1231 png_set_packing(png_ptr);
1233 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1236 /* Change the order of packed pixels to least significant bit first
1237 * (not useful if you are using png_set_packing).
1239 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1240 #ifdef PNG_READ_PACKSWAP_SUPPORTED
1241 png_set_packswap(png_ptr);
1243 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1246 /* Expand paletted colors into true RGB triplets
1247 * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
1248 * Expand paletted or RGB images with transparency to full alpha
1249 * channels so the data will be available as RGBA quartets.
1251 if ((transforms & PNG_TRANSFORM_EXPAND) != 0)
1252 #ifdef PNG_READ_EXPAND_SUPPORTED
1253 png_set_expand(png_ptr);
1255 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND not supported");
1258 /* We don't handle background color or gamma transformation or quantizing.
1261 /* Invert monochrome files to have 0 as white and 1 as black
1263 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1264 #ifdef PNG_READ_INVERT_SUPPORTED
1265 png_set_invert_mono(png_ptr);
1267 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1270 /* If you want to shift the pixel values from the range [0,255] or
1271 * [0,65535] to the original [0,7] or [0,31], or whatever range the
1272 * colors were originally in:
1274 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1275 #ifdef PNG_READ_SHIFT_SUPPORTED
1276 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1277 png_set_shift(png_ptr, &info_ptr->sig_bit);
1279 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1282 /* Flip the RGB pixels to BGR (or RGBA to BGRA) */
1283 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1284 #ifdef PNG_READ_BGR_SUPPORTED
1285 png_set_bgr(png_ptr);
1287 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1290 /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */
1291 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1292 #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
1293 png_set_swap_alpha(png_ptr);
1295 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1298 /* Swap bytes of 16-bit files to least significant byte first */
1299 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1300 #ifdef PNG_READ_SWAP_SUPPORTED
1301 png_set_swap(png_ptr);
1303 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1306 /* Added at libpng-1.2.41 */
1307 /* Invert the alpha channel from opacity to transparency */
1308 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1309 #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED
1310 png_set_invert_alpha(png_ptr);
1312 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1315 /* Added at libpng-1.2.41 */
1316 /* Expand grayscale image to RGB */
1317 if ((transforms & PNG_TRANSFORM_GRAY_TO_RGB) != 0)
1318 #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
1319 png_set_gray_to_rgb(png_ptr);
1321 png_app_error(png_ptr, "PNG_TRANSFORM_GRAY_TO_RGB not supported");
1324 /* Added at libpng-1.5.4 */
1325 if ((transforms & PNG_TRANSFORM_EXPAND_16) != 0)
1326 #ifdef PNG_READ_EXPAND_16_SUPPORTED
1327 png_set_expand_16(png_ptr);
1329 png_app_error(png_ptr, "PNG_TRANSFORM_EXPAND_16 not supported");
1332 /* We don't handle adding filler bytes */
1334 /* We use png_read_image and rely on that for interlace handling, but we also
1335 * call png_read_update_info therefore must turn on interlace handling now:
1337 (void)png_set_interlace_handling(png_ptr);
1339 /* Optional call to gamma correct and add the background to the palette
1340 * and update info structure. REQUIRED if you are expecting libpng to
1341 * update the palette for you (i.e., you selected such a transform above).
1343 png_read_update_info(png_ptr, info_ptr);
1345 /* -------------- image transformations end here ------------------- */
1347 png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
1348 if (info_ptr->row_pointers == NULL)
1352 info_ptr->row_pointers = png_voidcast(png_bytepp, png_malloc(png_ptr,
1353 info_ptr->height * (sizeof (png_bytep))));
1355 for (iptr=0; iptr<info_ptr->height; iptr++)
1356 info_ptr->row_pointers[iptr] = NULL;
1358 info_ptr->free_me |= PNG_FREE_ROWS;
1360 for (iptr = 0; iptr < info_ptr->height; iptr++)
1361 info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
1362 png_malloc(png_ptr, info_ptr->rowbytes));
1365 png_read_image(png_ptr, info_ptr->row_pointers);
1366 info_ptr->valid |= PNG_INFO_IDAT;
1368 /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */
1369 png_read_end(png_ptr, info_ptr);
1373 #endif /* INFO_IMAGE */
1374 #endif /* SEQUENTIAL_READ */
1376 #ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1379 * This code currently relies on the sequential reader, though it could easily
1380 * be made to work with the progressive one.
1382 /* Arguments to png_image_finish_read: */
1384 /* Encoding of PNG data (used by the color-map code) */
1385 # define P_NOTSET 0 /* File encoding not yet known */
1386 # define P_sRGB 1 /* 8-bit encoded to sRGB gamma */
1387 # define P_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */
1388 # define P_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */
1389 # define P_LINEAR8 4 /* 8-bit linear: only from a file value */
1391 /* Color-map processing: after libpng has run on the PNG image further
1392 * processing may be needed to convert the data to color-map indices.
1394 #define PNG_CMAP_NONE 0
1395 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */
1396 #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */
1397 #define PNG_CMAP_RGB 3 /* Process RGB data */
1398 #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */
1400 /* The following document where the background is for each processing case. */
1401 #define PNG_CMAP_NONE_BACKGROUND 256
1402 #define PNG_CMAP_GA_BACKGROUND 231
1403 #define PNG_CMAP_TRANS_BACKGROUND 254
1404 #define PNG_CMAP_RGB_BACKGROUND 256
1405 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216
1412 png_int_32 row_stride;
1414 png_const_colorp background;
1415 /* Local variables: */
1416 png_voidp local_row;
1417 png_voidp first_row;
1418 ptrdiff_t row_bytes; /* step between rows */
1419 int file_encoding; /* E_ values above */
1420 png_fixed_point gamma_to_linear; /* For P_FILE, reciprocal of gamma */
1421 int colormap_processing; /* PNG_CMAP_ values above */
1422 } png_image_read_control;
1424 /* Do all the *safe* initialization - 'safe' means that png_error won't be
1425 * called, so setting up the jmp_buf is not required. This means that anything
1426 * called from here must *not* call png_malloc - it has to call png_malloc_warn
1427 * instead so that control is returned safely back to this routine.
1430 png_image_read_init(png_imagep image)
1432 if (image->opaque == NULL)
1434 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image,
1435 png_safe_error, png_safe_warning);
1437 /* And set the rest of the structure to NULL to ensure that the various
1438 * fields are consistent.
1440 memset(image, 0, (sizeof *image));
1441 image->version = PNG_IMAGE_VERSION;
1443 if (png_ptr != NULL)
1445 png_infop info_ptr = png_create_info_struct(png_ptr);
1447 if (info_ptr != NULL)
1449 png_controlp control = png_voidcast(png_controlp,
1450 png_malloc_warn(png_ptr, (sizeof *control)));
1452 if (control != NULL)
1454 memset(control, 0, (sizeof *control));
1456 control->png_ptr = png_ptr;
1457 control->info_ptr = info_ptr;
1458 control->for_write = 0;
1460 image->opaque = control;
1464 /* Error clean up */
1465 png_destroy_info_struct(png_ptr, &info_ptr);
1468 png_destroy_read_struct(&png_ptr, NULL, NULL);
1471 return png_image_error(image, "png_image_read: out of memory");
1474 return png_image_error(image, "png_image_read: opaque pointer not NULL");
1477 /* Utility to find the base format of a PNG file from a png_struct. */
1479 png_image_format(png_structrp png_ptr)
1481 png_uint_32 format = 0;
1483 if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
1484 format |= PNG_FORMAT_FLAG_COLOR;
1486 if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
1487 format |= PNG_FORMAT_FLAG_ALPHA;
1489 /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS
1490 * sets the png_struct fields; that's all we are interested in here. The
1491 * precise interaction with an app call to png_set_tRNS and PNG file reading
1494 else if (png_ptr->num_trans > 0)
1495 format |= PNG_FORMAT_FLAG_ALPHA;
1497 if (png_ptr->bit_depth == 16)
1498 format |= PNG_FORMAT_FLAG_LINEAR;
1500 if ((png_ptr->color_type & PNG_COLOR_MASK_PALETTE) != 0)
1501 format |= PNG_FORMAT_FLAG_COLORMAP;
1506 /* Is the given gamma significantly different from sRGB? The test is the same
1507 * one used in pngrtran.c when deciding whether to do gamma correction. The
1508 * arithmetic optimizes the division by using the fact that the inverse of the
1509 * file sRGB gamma is 2.2
1512 png_gamma_not_sRGB(png_fixed_point g)
1516 /* An uninitialized gamma is assumed to be sRGB for the simplified API. */
1520 return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */);
1526 /* Do the main body of a 'png_image_begin_read' function; read the PNG file
1527 * header and fill in all the information. This is executed in a safe context,
1528 * unlike the init routine above.
1531 png_image_read_header(png_voidp argument)
1533 png_imagep image = png_voidcast(png_imagep, argument);
1534 png_structrp png_ptr = image->opaque->png_ptr;
1535 png_inforp info_ptr = image->opaque->info_ptr;
1537 #ifdef PNG_BENIGN_ERRORS_SUPPORTED
1538 png_set_benign_errors(png_ptr, 1/*warn*/);
1540 png_read_info(png_ptr, info_ptr);
1542 /* Do this the fast way; just read directly out of png_struct. */
1543 image->width = png_ptr->width;
1544 image->height = png_ptr->height;
1547 png_uint_32 format = png_image_format(png_ptr);
1549 image->format = format;
1551 #ifdef PNG_COLORSPACE_SUPPORTED
1552 /* Does the colorspace match sRGB? If there is no color endpoint
1553 * (colorant) information assume yes, otherwise require the
1554 * 'ENDPOINTS_MATCHP_sRGB' colorspace flag to have been set. If the
1555 * colorspace has been determined to be invalid ignore it.
1557 if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags
1558 & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB|
1559 PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS))
1560 image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB;
1564 /* We need the maximum number of entries regardless of the format the
1565 * application sets here.
1568 png_uint_32 cmap_entries;
1570 switch (png_ptr->color_type)
1572 case PNG_COLOR_TYPE_GRAY:
1573 cmap_entries = 1U << png_ptr->bit_depth;
1576 case PNG_COLOR_TYPE_PALETTE:
1577 cmap_entries = (png_uint_32)png_ptr->num_palette;
1585 if (cmap_entries > 256)
1588 image->colormap_entries = cmap_entries;
1594 #ifdef PNG_STDIO_SUPPORTED
1596 png_image_begin_read_from_stdio(png_imagep image, FILE* file)
1598 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1602 if (png_image_read_init(image) != 0)
1604 /* This is slightly evil, but png_init_io doesn't do anything other
1605 * than this and we haven't changed the standard IO functions so
1606 * this saves a 'safe' function.
1608 image->opaque->png_ptr->io_ptr = file;
1609 return png_safe_execute(image, png_image_read_header, image);
1614 return png_image_error(image,
1615 "png_image_begin_read_from_stdio: invalid argument");
1618 else if (image != NULL)
1619 return png_image_error(image,
1620 "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION");
1626 png_image_begin_read_from_file(png_imagep image, const char *file_name)
1628 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1630 if (file_name != NULL)
1632 FILE *fp = fopen(file_name, "rb");
1636 if (png_image_read_init(image) != 0)
1638 image->opaque->png_ptr->io_ptr = fp;
1639 image->opaque->owned_file = 1;
1640 return png_safe_execute(image, png_image_read_header, image);
1643 /* Clean up: just the opened file. */
1648 return png_image_error(image, strerror(errno));
1652 return png_image_error(image,
1653 "png_image_begin_read_from_file: invalid argument");
1656 else if (image != NULL)
1657 return png_image_error(image,
1658 "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION");
1664 static void PNGCBAPI
1665 png_image_memory_read(png_structp png_ptr, png_bytep out, size_t need)
1667 if (png_ptr != NULL)
1669 png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr);
1672 png_controlp cp = image->opaque;
1675 png_const_bytep memory = cp->memory;
1676 size_t size = cp->size;
1678 if (memory != NULL && size >= need)
1680 memcpy(out, memory, need);
1681 cp->memory = memory + need;
1682 cp->size = size - need;
1686 png_error(png_ptr, "read beyond end of data");
1690 png_error(png_ptr, "invalid memory read");
1694 int PNGAPI png_image_begin_read_from_memory(png_imagep image,
1695 png_const_voidp memory, size_t size)
1697 if (image != NULL && image->version == PNG_IMAGE_VERSION)
1699 if (memory != NULL && size > 0)
1701 if (png_image_read_init(image) != 0)
1703 /* Now set the IO functions to read from the memory buffer and
1704 * store it into io_ptr. Again do this in-place to avoid calling a
1705 * libpng function that requires error handling.
1707 image->opaque->memory = png_voidcast(png_const_bytep, memory);
1708 image->opaque->size = size;
1709 image->opaque->png_ptr->io_ptr = image;
1710 image->opaque->png_ptr->read_data_fn = png_image_memory_read;
1712 return png_safe_execute(image, png_image_read_header, image);
1717 return png_image_error(image,
1718 "png_image_begin_read_from_memory: invalid argument");
1721 else if (image != NULL)
1722 return png_image_error(image,
1723 "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION");
1728 /* Utility function to skip chunks that are not used by the simplified image
1729 * read functions and an appropriate macro to call it.
1731 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
1733 png_image_skip_unused_chunks(png_structrp png_ptr)
1735 /* Prepare the reader to ignore all recognized chunks whose data will not
1736 * be used, i.e., all chunks recognized by libpng except for those
1737 * involved in basic image reading:
1739 * IHDR, PLTE, IDAT, IEND
1741 * Or image data handling:
1743 * tRNS, bKGD, gAMA, cHRM, sRGB, [iCCP] and sBIT.
1745 * This provides a small performance improvement and eliminates any
1746 * potential vulnerability to security problems in the unused chunks.
1748 * At present the iCCP chunk data isn't used, so iCCP chunk can be ignored
1749 * too. This allows the simplified API to be compiled without iCCP support,
1750 * however if the support is there the chunk is still checked to detect
1751 * errors (which are unfortunately quite common.)
1754 static const png_byte chunks_to_process[] = {
1755 98, 75, 71, 68, '\0', /* bKGD */
1756 99, 72, 82, 77, '\0', /* cHRM */
1757 103, 65, 77, 65, '\0', /* gAMA */
1758 # ifdef PNG_READ_iCCP_SUPPORTED
1759 105, 67, 67, 80, '\0', /* iCCP */
1761 115, 66, 73, 84, '\0', /* sBIT */
1762 115, 82, 71, 66, '\0', /* sRGB */
1765 /* Ignore unknown chunks and all other chunks except for the
1766 * IHDR, PLTE, tRNS, IDAT, and IEND chunks.
1768 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER,
1771 /* But do not ignore image data handling chunks */
1772 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT,
1773 chunks_to_process, (int)/*SAFE*/(sizeof chunks_to_process)/5);
1777 # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p)
1779 # define PNG_SKIP_CHUNKS(p) ((void)0)
1780 #endif /* HANDLE_AS_UNKNOWN */
1782 /* The following macro gives the exact rounded answer for all values in the
1783 * range 0..255 (it actually divides by 51.2, but the rounding still generates
1784 * the correct numbers 0..5
1786 #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8)
1788 /* Utility functions to make particular color-maps */
1790 set_file_encoding(png_image_read_control *display)
1792 png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma;
1793 if (png_gamma_significant(g) != 0)
1795 if (png_gamma_not_sRGB(g) != 0)
1797 display->file_encoding = P_FILE;
1798 display->gamma_to_linear = png_reciprocal(g);
1802 display->file_encoding = P_sRGB;
1806 display->file_encoding = P_LINEAR8;
1810 decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
1812 if (encoding == P_FILE) /* double check */
1813 encoding = display->file_encoding;
1815 if (encoding == P_NOTSET) /* must be the file encoding */
1817 set_file_encoding(display);
1818 encoding = display->file_encoding;
1824 value = png_gamma_16bit_correct(value*257, display->gamma_to_linear);
1828 value = png_sRGB_table[value];
1840 png_error(display->image->opaque->png_ptr,
1841 "unexpected encoding (internal error)");
1849 png_colormap_compose(png_image_read_control *display,
1850 png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha,
1851 png_uint_32 background, int encoding)
1853 /* The file value is composed on the background, the background has the given
1854 * encoding and so does the result, the file is encoded with P_FILE and the
1855 * file and alpha are 8-bit values. The (output) encoding will always be
1856 * P_LINEAR or P_sRGB.
1858 png_uint_32 f = decode_gamma(display, foreground, foreground_encoding);
1859 png_uint_32 b = decode_gamma(display, background, encoding);
1861 /* The alpha is always an 8-bit value (it comes from the palette), the value
1862 * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires.
1864 f = f * alpha + b * (255-alpha);
1866 if (encoding == P_LINEAR)
1868 /* Scale to 65535; divide by 255, approximately (in fact this is extremely
1869 * accurate, it divides by 255.00000005937181414556, with no overflow.)
1871 f *= 257; /* Now scaled by 65535 */
1873 f = (f+32768) >> 16;
1877 f = PNG_sRGB_FROM_LINEAR(f);
1882 /* NOTE: P_LINEAR values to this routine must be 16-bit, but P_FILE values must
1886 png_create_colormap_entry(png_image_read_control *display,
1887 png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue,
1888 png_uint_32 alpha, int encoding)
1890 png_imagep image = display->image;
1891 int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
1893 int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 &&
1894 (red != green || green != blue);
1897 png_error(image->opaque->png_ptr, "color-map index out of range");
1899 /* Update the cache with whether the file gamma is significantly different
1902 if (encoding == P_FILE)
1904 if (display->file_encoding == P_NOTSET)
1905 set_file_encoding(display);
1907 /* Note that the cached value may be P_FILE too, but if it is then the
1908 * gamma_to_linear member has been set.
1910 encoding = display->file_encoding;
1913 if (encoding == P_FILE)
1915 png_fixed_point g = display->gamma_to_linear;
1917 red = png_gamma_16bit_correct(red*257, g);
1918 green = png_gamma_16bit_correct(green*257, g);
1919 blue = png_gamma_16bit_correct(blue*257, g);
1921 if (convert_to_Y != 0 || output_encoding == P_LINEAR)
1924 encoding = P_LINEAR;
1929 red = PNG_sRGB_FROM_LINEAR(red * 255);
1930 green = PNG_sRGB_FROM_LINEAR(green * 255);
1931 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1936 else if (encoding == P_LINEAR8)
1938 /* This encoding occurs quite frequently in test cases because PngSuite
1939 * includes a gAMA 1.0 chunk with most images.
1945 encoding = P_LINEAR;
1948 else if (encoding == P_sRGB &&
1949 (convert_to_Y != 0 || output_encoding == P_LINEAR))
1951 /* The values are 8-bit sRGB values, but must be converted to 16-bit
1954 red = png_sRGB_table[red];
1955 green = png_sRGB_table[green];
1956 blue = png_sRGB_table[blue];
1958 encoding = P_LINEAR;
1961 /* This is set if the color isn't gray but the output is. */
1962 if (encoding == P_LINEAR)
1964 if (convert_to_Y != 0)
1966 /* NOTE: these values are copied from png_do_rgb_to_gray */
1967 png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green +
1968 (png_uint_32)2366 * blue;
1970 if (output_encoding == P_LINEAR)
1971 y = (y + 16384) >> 15;
1975 /* y is scaled by 32768, we need it scaled by 255: */
1978 y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7);
1979 alpha = PNG_DIV257(alpha);
1983 blue = red = green = y;
1986 else if (output_encoding == P_sRGB)
1988 red = PNG_sRGB_FROM_LINEAR(red * 255);
1989 green = PNG_sRGB_FROM_LINEAR(green * 255);
1990 blue = PNG_sRGB_FROM_LINEAR(blue * 255);
1991 alpha = PNG_DIV257(alpha);
1996 if (encoding != output_encoding)
1997 png_error(image->opaque->png_ptr, "bad encoding (internal error)");
1999 /* Store the value. */
2001 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
2002 int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
2003 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0;
2007 # ifdef PNG_FORMAT_BGR_SUPPORTED
2008 int bgr = (image->format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
2013 if (output_encoding == P_LINEAR)
2015 png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap);
2017 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2019 /* The linear 16-bit values must be pre-multiplied by the alpha channel
2020 * value, if less than 65535 (this is, effectively, composite on black
2021 * if the alpha channel is removed.)
2023 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2026 entry[afirst ? 0 : 3] = (png_uint_16)alpha;
2034 blue = (blue * alpha + 32767U)/65535U;
2035 green = (green * alpha + 32767U)/65535U;
2036 red = (red * alpha + 32767U)/65535U;
2040 red = green = blue = 0;
2042 entry[afirst + (2 ^ bgr)] = (png_uint_16)blue;
2043 entry[afirst + 1] = (png_uint_16)green;
2044 entry[afirst + bgr] = (png_uint_16)red;
2048 entry[1 ^ afirst] = (png_uint_16)alpha;
2055 green = (green * alpha + 32767U)/65535U;
2060 entry[afirst] = (png_uint_16)green;
2068 else /* output encoding is P_sRGB */
2070 png_bytep entry = png_voidcast(png_bytep, display->colormap);
2072 entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format);
2074 switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format))
2077 entry[afirst ? 0 : 3] = (png_byte)alpha;
2080 entry[afirst + (2 ^ bgr)] = (png_byte)blue;
2081 entry[afirst + 1] = (png_byte)green;
2082 entry[afirst + bgr] = (png_byte)red;
2086 entry[1 ^ afirst] = (png_byte)alpha;
2089 entry[afirst] = (png_byte)green;
2107 make_gray_file_colormap(png_image_read_control *display)
2111 for (i=0; i<256; ++i)
2112 png_create_colormap_entry(display, i, i, i, i, 255, P_FILE);
2118 make_gray_colormap(png_image_read_control *display)
2122 for (i=0; i<256; ++i)
2123 png_create_colormap_entry(display, i, i, i, i, 255, P_sRGB);
2127 #define PNG_GRAY_COLORMAP_ENTRIES 256
2130 make_ga_colormap(png_image_read_control *display)
2134 /* Alpha is retained, the output will be a color-map with entries
2135 * selected by six levels of alpha. One transparent entry, 6 gray
2136 * levels for all the intermediate alpha values, leaving 230 entries
2137 * for the opaque grays. The color-map entries are the six values
2138 * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the
2141 * if (alpha > 229) // opaque
2143 * // The 231 entries are selected to make the math below work:
2145 * entry = (231 * gray + 128) >> 8;
2147 * else if (alpha < 26) // transparent
2152 * else // partially opaque
2154 * base = 226 + 6 * PNG_DIV51(alpha);
2155 * entry = PNG_DIV51(gray);
2161 unsigned int gray = (i * 256 + 115) / 231;
2162 png_create_colormap_entry(display, i++, gray, gray, gray, 255, P_sRGB);
2165 /* 255 is used here for the component values for consistency with the code
2166 * that undoes premultiplication in pngwrite.c.
2168 png_create_colormap_entry(display, i++, 255, 255, 255, 0, P_sRGB);
2175 png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51,
2182 #define PNG_GA_COLORMAP_ENTRIES 256
2185 make_rgb_colormap(png_image_read_control *display)
2189 /* Build a 6x6x6 opaque RGB cube */
2190 for (i=r=0; r<6; ++r)
2199 png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255,
2207 #define PNG_RGB_COLORMAP_ENTRIES 216
2209 /* Return a palette index to the above palette given three 8-bit sRGB values. */
2210 #define PNG_RGB_INDEX(r,g,b) \
2211 ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b)))
2214 png_image_read_colormap(png_voidp argument)
2216 png_image_read_control *display =
2217 png_voidcast(png_image_read_control*, argument);
2218 png_imagep image = display->image;
2220 png_structrp png_ptr = image->opaque->png_ptr;
2221 png_uint_32 output_format = image->format;
2222 int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) != 0 ?
2225 unsigned int cmap_entries;
2226 unsigned int output_processing; /* Output processing option */
2227 unsigned int data_encoding = P_NOTSET; /* Encoding libpng must produce */
2229 /* Background information; the background color and the index of this color
2230 * in the color-map if it exists (else 256).
2232 unsigned int background_index = 256;
2233 png_uint_32 back_r, back_g, back_b;
2235 /* Flags to accumulate things that need to be done to the input. */
2236 int expand_tRNS = 0;
2238 /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is
2239 * very difficult to do, the results look awful, and it is difficult to see
2240 * what possible use it is because the application can't control the
2243 if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 ||
2244 png_ptr->num_trans > 0) /* alpha in input */ &&
2245 ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */)
2247 if (output_encoding == P_LINEAR) /* compose on black */
2248 back_b = back_g = back_r = 0;
2250 else if (display->background == NULL /* no way to remove it */)
2252 "background color must be supplied to remove alpha/transparency");
2254 /* Get a copy of the background color (this avoids repeating the checks
2255 * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the
2260 back_g = display->background->green;
2261 if ((output_format & PNG_FORMAT_FLAG_COLOR) != 0)
2263 back_r = display->background->red;
2264 back_b = display->background->blue;
2267 back_b = back_r = back_g;
2271 else if (output_encoding == P_LINEAR)
2272 back_b = back_r = back_g = 65535;
2275 back_b = back_r = back_g = 255;
2277 /* Default the input file gamma if required - this is necessary because
2278 * libpng assumes that if no gamma information is present the data is in the
2279 * output format, but the simplified API deduces the gamma from the input
2282 if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0)
2284 /* Do this directly, not using the png_colorspace functions, to ensure
2285 * that it happens even if the colorspace is invalid (though probably if
2286 * it is the setting will be ignored) Note that the same thing can be
2287 * achieved at the application interface with png_set_gAMA.
2289 if (png_ptr->bit_depth == 16 &&
2290 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
2291 png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR;
2294 png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE;
2296 png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
2299 /* Decide what to do based on the PNG color type of the input data. The
2300 * utility function png_create_colormap_entry deals with most aspects of the
2301 * output transformations; this code works out how to produce bytes of
2302 * color-map entries from the original format.
2304 switch (png_ptr->color_type)
2306 case PNG_COLOR_TYPE_GRAY:
2307 if (png_ptr->bit_depth <= 8)
2309 /* There at most 256 colors in the output, regardless of
2312 unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0;
2314 cmap_entries = 1U << png_ptr->bit_depth;
2315 if (cmap_entries > image->colormap_entries)
2316 png_error(png_ptr, "gray[8] color-map: too few entries");
2318 step = 255 / (cmap_entries - 1);
2319 output_processing = PNG_CMAP_NONE;
2321 /* If there is a tRNS chunk then this either selects a transparent
2322 * value or, if the output has no alpha, the background color.
2324 if (png_ptr->num_trans > 0)
2326 trans = png_ptr->trans_color.gray;
2328 if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0)
2329 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2332 /* png_create_colormap_entry just takes an RGBA and writes the
2333 * corresponding color-map entry using the format from 'image',
2334 * including the required conversion to sRGB or linear as
2335 * appropriate. The input values are always either sRGB (if the
2336 * gamma correction flag is 0) or 0..255 scaled file encoded values
2337 * (if the function must gamma correct them).
2339 for (i=val=0; i<cmap_entries; ++i, val += step)
2341 /* 'i' is a file value. While this will result in duplicated
2342 * entries for 8-bit non-sRGB encoded files it is necessary to
2343 * have non-gamma corrected values to do tRNS handling.
2346 png_create_colormap_entry(display, i, val, val, val, 255,
2347 P_FILE/*8-bit with file gamma*/);
2349 /* Else this entry is transparent. The colors don't matter if
2350 * there is an alpha channel (back_alpha == 0), but it does no
2351 * harm to pass them in; the values are not set above so this
2354 * NOTE: this preserves the full precision of the application
2355 * supplied background color when it is used.
2358 png_create_colormap_entry(display, i, back_r, back_g, back_b,
2359 back_alpha, output_encoding);
2362 /* We need libpng to preserve the original encoding. */
2363 data_encoding = P_FILE;
2365 /* The rows from libpng, while technically gray values, are now also
2366 * color-map indices; however, they may need to be expanded to 1
2367 * byte per pixel. This is what png_set_packing does (i.e., it
2368 * unpacks the bit values into bytes.)
2370 if (png_ptr->bit_depth < 8)
2371 png_set_packing(png_ptr);
2374 else /* bit depth is 16 */
2376 /* The 16-bit input values can be converted directly to 8-bit gamma
2377 * encoded values; however, if a tRNS chunk is present 257 color-map
2378 * entries are required. This means that the extra entry requires
2379 * special processing; add an alpha channel, sacrifice gray level
2380 * 254 and convert transparent (alpha==0) entries to that.
2382 * Use libpng to chop the data to 8 bits. Convert it to sRGB at the
2383 * same time to minimize quality loss. If a tRNS chunk is present
2384 * this means libpng must handle it too; otherwise it is impossible
2385 * to do the exact match on the 16-bit value.
2387 * If the output has no alpha channel *and* the background color is
2388 * gray then it is possible to let libpng handle the substitution by
2389 * ensuring that the corresponding gray level matches the background
2392 data_encoding = P_sRGB;
2394 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2395 png_error(png_ptr, "gray[16] color-map: too few entries");
2397 cmap_entries = (unsigned int)make_gray_colormap(display);
2399 if (png_ptr->num_trans > 0)
2401 unsigned int back_alpha;
2403 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2408 if (back_r == back_g && back_g == back_b)
2410 /* Background is gray; no special processing will be
2414 png_uint_32 gray = back_g;
2416 if (output_encoding == P_LINEAR)
2418 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2420 /* And make sure the corresponding palette entry
2423 png_create_colormap_entry(display, gray, back_g, back_g,
2424 back_g, 65535, P_LINEAR);
2427 /* The background passed to libpng, however, must be the
2430 c.index = 0; /*unused*/
2431 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2433 /* NOTE: does this work without expanding tRNS to alpha?
2434 * It should be the color->gray case below apparently
2437 png_set_background_fixed(png_ptr, &c,
2438 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2439 0/*gamma: not used*/);
2441 output_processing = PNG_CMAP_NONE;
2445 /* Coverity claims that output_encoding cannot be 2 (P_LINEAR)
2450 back_alpha = output_encoding == P_LINEAR ? 65535 : 255;
2454 /* output_processing means that the libpng-processed row will be
2455 * 8-bit GA and it has to be processing to single byte color-map
2456 * values. Entry 254 is replaced by either a completely
2457 * transparent entry or by the background color at full
2458 * precision (and the background color is not a simple gray
2459 * level in this case.)
2462 output_processing = PNG_CMAP_TRANS;
2463 background_index = 254;
2465 /* And set (overwrite) color-map entry 254 to the actual
2466 * background color at full precision.
2468 png_create_colormap_entry(display, 254, back_r, back_g, back_b,
2469 back_alpha, output_encoding);
2473 output_processing = PNG_CMAP_NONE;
2477 case PNG_COLOR_TYPE_GRAY_ALPHA:
2478 /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum
2479 * of 65536 combinations. If, however, the alpha channel is to be
2480 * removed there are only 256 possibilities if the background is gray.
2481 * (Otherwise there is a subset of the 65536 possibilities defined by
2482 * the triangle between black, white and the background color.)
2484 * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to
2485 * worry about tRNS matching - tRNS is ignored if there is an alpha
2488 data_encoding = P_sRGB;
2490 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2492 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2493 png_error(png_ptr, "gray+alpha color-map: too few entries");
2495 cmap_entries = (unsigned int)make_ga_colormap(display);
2497 background_index = PNG_CMAP_GA_BACKGROUND;
2498 output_processing = PNG_CMAP_GA;
2501 else /* alpha is removed */
2503 /* Alpha must be removed as the PNG data is processed when the
2504 * background is a color because the G and A channels are
2505 * independent and the vector addition (non-parallel vectors) is a
2508 * This can be reduced to the same algorithm as above by making a
2509 * colormap containing gray levels (for the opaque grays), a
2510 * background entry (for a transparent pixel) and a set of four six
2511 * level color values, one set for each intermediate alpha value.
2512 * See the comments in make_ga_colormap for how this works in the
2513 * per-pixel processing.
2515 * If the background is gray, however, we only need a 256 entry gray
2516 * level color map. It is sufficient to make the entry generated
2517 * for the background color be exactly the color specified.
2519 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 ||
2520 (back_r == back_g && back_g == back_b))
2522 /* Background is gray; no special processing will be required. */
2524 png_uint_32 gray = back_g;
2526 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2527 png_error(png_ptr, "gray-alpha color-map: too few entries");
2529 cmap_entries = (unsigned int)make_gray_colormap(display);
2531 if (output_encoding == P_LINEAR)
2533 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2535 /* And make sure the corresponding palette entry matches. */
2536 png_create_colormap_entry(display, gray, back_g, back_g,
2537 back_g, 65535, P_LINEAR);
2540 /* The background passed to libpng, however, must be the sRGB
2543 c.index = 0; /*unused*/
2544 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2546 png_set_background_fixed(png_ptr, &c,
2547 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2548 0/*gamma: not used*/);
2550 output_processing = PNG_CMAP_NONE;
2557 /* This is the same as png_make_ga_colormap, above, except that
2558 * the entries are all opaque.
2560 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2561 png_error(png_ptr, "ga-alpha color-map: too few entries");
2566 png_uint_32 gray = (i * 256 + 115) / 231;
2567 png_create_colormap_entry(display, i++, gray, gray, gray,
2571 /* NOTE: this preserves the full precision of the application
2574 background_index = i;
2575 png_create_colormap_entry(display, i++, back_r, back_g, back_b,
2577 /* Coverity claims that output_encoding
2578 * cannot be 2 (P_LINEAR) here.
2581 output_encoding == P_LINEAR ? 65535U : 255U,
2585 /* For non-opaque input composite on the sRGB background - this
2586 * requires inverting the encoding for each component. The input
2587 * is still converted to the sRGB encoding because this is a
2588 * reasonable approximate to the logarithmic curve of human
2589 * visual sensitivity, at least over the narrow range which PNG
2590 * represents. Consequently 'G' is always sRGB encoded, while
2591 * 'A' is linear. We need the linear background colors.
2593 if (output_encoding == P_sRGB) /* else already linear */
2595 /* This may produce a value not exactly matching the
2596 * background, but that's ok because these numbers are only
2597 * used when alpha != 0
2599 back_r = png_sRGB_table[back_r];
2600 back_g = png_sRGB_table[back_g];
2601 back_b = png_sRGB_table[back_b];
2608 /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled
2609 * by an 8-bit alpha value (0..255).
2611 png_uint_32 alpha = 51 * a;
2612 png_uint_32 back_rx = (255-alpha) * back_r;
2613 png_uint_32 back_gx = (255-alpha) * back_g;
2614 png_uint_32 back_bx = (255-alpha) * back_b;
2618 png_uint_32 gray = png_sRGB_table[g*51] * alpha;
2620 png_create_colormap_entry(display, i++,
2621 PNG_sRGB_FROM_LINEAR(gray + back_rx),
2622 PNG_sRGB_FROM_LINEAR(gray + back_gx),
2623 PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, P_sRGB);
2628 output_processing = PNG_CMAP_GA;
2633 case PNG_COLOR_TYPE_RGB:
2634 case PNG_COLOR_TYPE_RGB_ALPHA:
2635 /* Exclude the case where the output is gray; we can always handle this
2636 * with the cases above.
2638 if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0)
2640 /* The color-map will be grayscale, so we may as well convert the
2641 * input RGB values to a simple grayscale and use the grayscale
2644 * NOTE: calling this apparently damages the recognition of the
2645 * transparent color in background color handling; call
2646 * png_set_tRNS_to_alpha before png_set_background_fixed.
2648 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1,
2650 data_encoding = P_sRGB;
2652 /* The output will now be one or two 8-bit gray or gray+alpha
2653 * channels. The more complex case arises when the input has alpha.
2655 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2656 png_ptr->num_trans > 0) &&
2657 (output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2659 /* Both input and output have an alpha channel, so no background
2660 * processing is required; just map the GA bytes to the right
2665 if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries)
2666 png_error(png_ptr, "rgb[ga] color-map: too few entries");
2668 cmap_entries = (unsigned int)make_ga_colormap(display);
2669 background_index = PNG_CMAP_GA_BACKGROUND;
2670 output_processing = PNG_CMAP_GA;
2675 /* Either the input or the output has no alpha channel, so there
2676 * will be no non-opaque pixels in the color-map; it will just be
2679 if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries)
2680 png_error(png_ptr, "rgb[gray] color-map: too few entries");
2682 /* Ideally this code would use libpng to do the gamma correction,
2683 * but if an input alpha channel is to be removed we will hit the
2684 * libpng bug in gamma+compose+rgb-to-gray (the double gamma
2685 * correction bug). Fix this by dropping the gamma correction in
2686 * this case and doing it in the palette; this will result in
2687 * duplicate palette entries, but that's better than the
2688 * alternative of double gamma correction.
2690 if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2691 png_ptr->num_trans > 0) &&
2692 png_gamma_not_sRGB(png_ptr->colorspace.gamma) != 0)
2694 cmap_entries = (unsigned int)make_gray_file_colormap(display);
2695 data_encoding = P_FILE;
2699 cmap_entries = (unsigned int)make_gray_colormap(display);
2701 /* But if the input has alpha or transparency it must be removed
2703 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2704 png_ptr->num_trans > 0)
2707 png_uint_32 gray = back_g;
2709 /* We need to ensure that the application background exists in
2710 * the colormap and that completely transparent pixels map to
2711 * it. Achieve this simply by ensuring that the entry
2712 * selected for the background really is the background color.
2714 if (data_encoding == P_FILE) /* from the fixup above */
2716 /* The app supplied a gray which is in output_encoding, we
2717 * need to convert it to a value of the input (P_FILE)
2718 * encoding then set this palette entry to the required
2721 if (output_encoding == P_sRGB)
2722 gray = png_sRGB_table[gray]; /* now P_LINEAR */
2724 gray = PNG_DIV257(png_gamma_16bit_correct(gray,
2725 png_ptr->colorspace.gamma)); /* now P_FILE */
2727 /* And make sure the corresponding palette entry contains
2728 * exactly the required sRGB value.
2730 png_create_colormap_entry(display, gray, back_g, back_g,
2731 back_g, 0/*unused*/, output_encoding);
2734 else if (output_encoding == P_LINEAR)
2736 gray = PNG_sRGB_FROM_LINEAR(gray * 255);
2738 /* And make sure the corresponding palette entry matches.
2740 png_create_colormap_entry(display, gray, back_g, back_g,
2741 back_g, 0/*unused*/, P_LINEAR);
2744 /* The background passed to libpng, however, must be the
2745 * output (normally sRGB) value.
2747 c.index = 0; /*unused*/
2748 c.gray = c.red = c.green = c.blue = (png_uint_16)gray;
2750 /* NOTE: the following is apparently a bug in libpng. Without
2751 * it the transparent color recognition in
2752 * png_set_background_fixed seems to go wrong.
2755 png_set_background_fixed(png_ptr, &c,
2756 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2757 0/*gamma: not used*/);
2760 output_processing = PNG_CMAP_NONE;
2764 else /* output is color */
2766 /* We could use png_quantize here so long as there is no transparent
2767 * color or alpha; png_quantize ignores alpha. Easier overall just
2768 * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube.
2769 * Consequently we always want libpng to produce sRGB data.
2771 data_encoding = P_sRGB;
2773 /* Is there any transparency or alpha? */
2774 if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
2775 png_ptr->num_trans > 0)
2777 /* Is there alpha in the output too? If so all four channels are
2778 * processed into a special RGB cube with alpha support.
2780 if ((output_format & PNG_FORMAT_FLAG_ALPHA) != 0)
2784 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2785 png_error(png_ptr, "rgb+alpha color-map: too few entries");
2787 cmap_entries = (unsigned int)make_rgb_colormap(display);
2789 /* Add a transparent entry. */
2790 png_create_colormap_entry(display, cmap_entries, 255, 255,
2793 /* This is stored as the background index for the processing
2796 background_index = cmap_entries++;
2798 /* Add 27 r,g,b entries each with alpha 0.5. */
2799 for (r=0; r<256; r = (r << 1) | 0x7f)
2803 for (g=0; g<256; g = (g << 1) | 0x7f)
2807 /* This generates components with the values 0, 127 and
2810 for (b=0; b<256; b = (b << 1) | 0x7f)
2811 png_create_colormap_entry(display, cmap_entries++,
2812 r, g, b, 128, P_sRGB);
2817 output_processing = PNG_CMAP_RGB_ALPHA;
2822 /* Alpha/transparency must be removed. The background must
2823 * exist in the color map (achieved by setting adding it after
2824 * the 666 color-map). If the standard processing code will
2825 * pick up this entry automatically that's all that is
2826 * required; libpng can be called to do the background
2829 unsigned int sample_size =
2830 PNG_IMAGE_SAMPLE_SIZE(output_format);
2831 png_uint_32 r, g, b; /* sRGB background */
2833 if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries)
2834 png_error(png_ptr, "rgb-alpha color-map: too few entries");
2836 cmap_entries = (unsigned int)make_rgb_colormap(display);
2838 png_create_colormap_entry(display, cmap_entries, back_r,
2839 back_g, back_b, 0/*unused*/, output_encoding);
2841 if (output_encoding == P_LINEAR)
2843 r = PNG_sRGB_FROM_LINEAR(back_r * 255);
2844 g = PNG_sRGB_FROM_LINEAR(back_g * 255);
2845 b = PNG_sRGB_FROM_LINEAR(back_b * 255);
2855 /* Compare the newly-created color-map entry with the one the
2856 * PNG_CMAP_RGB algorithm will use. If the two entries don't
2857 * match, add the new one and set this as the background
2860 if (memcmp((png_const_bytep)display->colormap +
2861 sample_size * cmap_entries,
2862 (png_const_bytep)display->colormap +
2863 sample_size * PNG_RGB_INDEX(r,g,b),
2866 /* The background color must be added. */
2867 background_index = cmap_entries++;
2869 /* Add 27 r,g,b entries each with created by composing with
2870 * the background at alpha 0.5.
2872 for (r=0; r<256; r = (r << 1) | 0x7f)
2874 for (g=0; g<256; g = (g << 1) | 0x7f)
2876 /* This generates components with the values 0, 127
2879 for (b=0; b<256; b = (b << 1) | 0x7f)
2880 png_create_colormap_entry(display, cmap_entries++,
2881 png_colormap_compose(display, r, P_sRGB, 128,
2882 back_r, output_encoding),
2883 png_colormap_compose(display, g, P_sRGB, 128,
2884 back_g, output_encoding),
2885 png_colormap_compose(display, b, P_sRGB, 128,
2886 back_b, output_encoding),
2887 0/*unused*/, output_encoding);
2892 output_processing = PNG_CMAP_RGB_ALPHA;
2895 else /* background color is in the standard color-map */
2899 c.index = 0; /*unused*/
2900 c.red = (png_uint_16)back_r;
2901 c.gray = c.green = (png_uint_16)back_g;
2902 c.blue = (png_uint_16)back_b;
2904 png_set_background_fixed(png_ptr, &c,
2905 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
2906 0/*gamma: not used*/);
2908 output_processing = PNG_CMAP_RGB;
2913 else /* no alpha or transparency in the input */
2915 /* Alpha in the output is irrelevant, simply map the opaque input
2916 * pixels to the 6x6x6 color-map.
2918 if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries)
2919 png_error(png_ptr, "rgb color-map: too few entries");
2921 cmap_entries = (unsigned int)make_rgb_colormap(display);
2922 output_processing = PNG_CMAP_RGB;
2927 case PNG_COLOR_TYPE_PALETTE:
2928 /* It's already got a color-map. It may be necessary to eliminate the
2929 * tRNS entries though.
2932 unsigned int num_trans = png_ptr->num_trans;
2933 png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL;
2934 png_const_colorp colormap = png_ptr->palette;
2935 int do_background = trans != NULL &&
2936 (output_format & PNG_FORMAT_FLAG_ALPHA) == 0;
2943 output_processing = PNG_CMAP_NONE;
2944 data_encoding = P_FILE; /* Don't change from color-map indices */
2945 cmap_entries = (unsigned int)png_ptr->num_palette;
2946 if (cmap_entries > 256)
2949 if (cmap_entries > (unsigned int)image->colormap_entries)
2950 png_error(png_ptr, "palette color-map: too few entries");
2952 for (i=0; i < cmap_entries; ++i)
2954 if (do_background != 0 && i < num_trans && trans[i] < 255)
2957 png_create_colormap_entry(display, i, back_r, back_g,
2958 back_b, 0, output_encoding);
2962 /* Must compose the PNG file color in the color-map entry
2963 * on the sRGB color in 'back'.
2965 png_create_colormap_entry(display, i,
2966 png_colormap_compose(display, colormap[i].red,
2967 P_FILE, trans[i], back_r, output_encoding),
2968 png_colormap_compose(display, colormap[i].green,
2969 P_FILE, trans[i], back_g, output_encoding),
2970 png_colormap_compose(display, colormap[i].blue,
2971 P_FILE, trans[i], back_b, output_encoding),
2972 output_encoding == P_LINEAR ? trans[i] * 257U :
2979 png_create_colormap_entry(display, i, colormap[i].red,
2980 colormap[i].green, colormap[i].blue,
2981 i < num_trans ? trans[i] : 255U, P_FILE/*8-bit*/);
2984 /* The PNG data may have indices packed in fewer than 8 bits, it
2985 * must be expanded if so.
2987 if (png_ptr->bit_depth < 8)
2988 png_set_packing(png_ptr);
2993 png_error(png_ptr, "invalid PNG color type");
2997 /* Now deal with the output processing */
2998 if (expand_tRNS != 0 && png_ptr->num_trans > 0 &&
2999 (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0)
3000 png_set_tRNS_to_alpha(png_ptr);
3002 switch (data_encoding)
3005 /* Change to 8-bit sRGB */
3006 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
3010 if (png_ptr->bit_depth > 8)
3011 png_set_scale_16(png_ptr);
3016 png_error(png_ptr, "bad data option (internal error)");
3020 if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
3021 png_error(png_ptr, "color map overflow (BAD internal error)");
3023 image->colormap_entries = cmap_entries;
3025 /* Double check using the recorded background index */
3026 switch (output_processing)
3029 if (background_index != PNG_CMAP_NONE_BACKGROUND)
3030 goto bad_background;
3034 if (background_index != PNG_CMAP_GA_BACKGROUND)
3035 goto bad_background;
3038 case PNG_CMAP_TRANS:
3039 if (background_index >= cmap_entries ||
3040 background_index != PNG_CMAP_TRANS_BACKGROUND)
3041 goto bad_background;
3045 if (background_index != PNG_CMAP_RGB_BACKGROUND)
3046 goto bad_background;
3049 case PNG_CMAP_RGB_ALPHA:
3050 if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND)
3051 goto bad_background;
3055 png_error(png_ptr, "bad processing option (internal error)");
3058 png_error(png_ptr, "bad background index (internal error)");
3061 display->colormap_processing = (int)output_processing;
3066 /* The final part of the color-map read called from png_image_finish_read. */
3068 png_image_read_and_map(png_voidp argument)
3070 png_image_read_control *display = png_voidcast(png_image_read_control*,
3072 png_imagep image = display->image;
3073 png_structrp png_ptr = image->opaque->png_ptr;
3076 /* Called when the libpng data must be transformed into the color-mapped
3077 * form. There is a local row buffer in display->local and this routine must
3078 * do the interlace handling.
3080 switch (png_ptr->interlaced)
3082 case PNG_INTERLACE_NONE:
3086 case PNG_INTERLACE_ADAM7:
3087 passes = PNG_INTERLACE_ADAM7_PASSES;
3091 png_error(png_ptr, "unknown interlace type");
3095 png_uint_32 height = image->height;
3096 png_uint_32 width = image->width;
3097 int proc = display->colormap_processing;
3098 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3099 ptrdiff_t step_row = display->row_bytes;
3102 for (pass = 0; pass < passes; ++pass)
3104 unsigned int startx, stepx, stepy;
3107 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3109 /* The row may be empty for a short image: */
3110 if (PNG_PASS_COLS(width, pass) == 0)
3113 startx = PNG_PASS_START_COL(pass);
3114 stepx = PNG_PASS_COL_OFFSET(pass);
3115 y = PNG_PASS_START_ROW(pass);
3116 stepy = PNG_PASS_ROW_OFFSET(pass);
3126 for (; y<height; y += stepy)
3128 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3129 png_bytep outrow = first_row + y * step_row;
3130 png_const_bytep end_row = outrow + width;
3132 /* Read read the libpng data into the temporary buffer. */
3133 png_read_row(png_ptr, inrow, NULL);
3135 /* Now process the row according to the processing option, note
3136 * that the caller verifies that the format of the libpng output
3137 * data is as required.
3143 for (; outrow < end_row; outrow += stepx)
3145 /* The data is always in the PNG order */
3146 unsigned int gray = *inrow++;
3147 unsigned int alpha = *inrow++;
3150 /* NOTE: this code is copied as a comment in
3151 * make_ga_colormap above. Please update the
3152 * comment if you change this code!
3154 if (alpha > 229) /* opaque */
3156 entry = (231 * gray + 128) >> 8;
3158 else if (alpha < 26) /* transparent */
3162 else /* partially opaque */
3164 entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray);
3167 *outrow = (png_byte)entry;
3171 case PNG_CMAP_TRANS:
3172 for (; outrow < end_row; outrow += stepx)
3174 png_byte gray = *inrow++;
3175 png_byte alpha = *inrow++;
3178 *outrow = PNG_CMAP_TRANS_BACKGROUND;
3180 else if (gray != PNG_CMAP_TRANS_BACKGROUND)
3184 *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1);
3189 for (; outrow < end_row; outrow += stepx)
3191 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]);
3196 case PNG_CMAP_RGB_ALPHA:
3197 for (; outrow < end_row; outrow += stepx)
3199 unsigned int alpha = inrow[3];
3201 /* Because the alpha entries only hold alpha==0.5 values
3202 * split the processing at alpha==0.25 (64) and 0.75
3207 *outrow = PNG_RGB_INDEX(inrow[0], inrow[1],
3210 else if (alpha < 64)
3211 *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND;
3215 /* Likewise there are three entries for each of r, g
3216 * and b. We could select the entry by popcount on
3217 * the top two bits on those architectures that
3218 * support it, this is what the code below does,
3221 unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1;
3223 /* Here are how the values map:
3229 * So, as above with the explicit alpha checks, the
3230 * breakpoints are at 64 and 196.
3232 if (inrow[0] & 0x80) back_i += 9; /* red */
3233 if (inrow[0] & 0x40) back_i += 9;
3234 if (inrow[0] & 0x80) back_i += 3; /* green */
3235 if (inrow[0] & 0x40) back_i += 3;
3236 if (inrow[0] & 0x80) back_i += 1; /* blue */
3237 if (inrow[0] & 0x40) back_i += 1;
3239 *outrow = (png_byte)back_i;
3257 png_image_read_colormapped(png_voidp argument)
3259 png_image_read_control *display = png_voidcast(png_image_read_control*,
3261 png_imagep image = display->image;
3262 png_controlp control = image->opaque;
3263 png_structrp png_ptr = control->png_ptr;
3264 png_inforp info_ptr = control->info_ptr;
3266 int passes = 0; /* As a flag */
3268 PNG_SKIP_CHUNKS(png_ptr);
3270 /* Update the 'info' structure and make sure the result is as required; first
3271 * make sure to turn on the interlace handling if it will be required
3272 * (because it can't be turned on *after* the call to png_read_update_info!)
3274 if (display->colormap_processing == PNG_CMAP_NONE)
3275 passes = png_set_interlace_handling(png_ptr);
3277 png_read_update_info(png_ptr, info_ptr);
3279 /* The expected output can be deduced from the colormap_processing option. */
3280 switch (display->colormap_processing)
3283 /* Output must be one channel and one byte per pixel, the output
3284 * encoding can be anything.
3286 if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
3287 info_ptr->color_type == PNG_COLOR_TYPE_GRAY) &&
3288 info_ptr->bit_depth == 8)
3293 case PNG_CMAP_TRANS:
3295 /* Output must be two channels and the 'G' one must be sRGB, the latter
3296 * can be checked with an exact number because it should have been set
3297 * to this number above!
3299 if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
3300 info_ptr->bit_depth == 8 &&
3301 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3302 image->colormap_entries == 256)
3308 /* Output must be 8-bit sRGB encoded RGB */
3309 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB &&
3310 info_ptr->bit_depth == 8 &&
3311 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3312 image->colormap_entries == 216)
3317 case PNG_CMAP_RGB_ALPHA:
3318 /* Output must be 8-bit sRGB encoded RGBA */
3319 if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
3320 info_ptr->bit_depth == 8 &&
3321 png_ptr->screen_gamma == PNG_GAMMA_sRGB &&
3322 image->colormap_entries == 244 /* 216 + 1 + 27 */)
3329 png_error(png_ptr, "bad color-map processing (internal error)");
3332 /* Now read the rows. Do this here if it is possible to read directly into
3333 * the output buffer, otherwise allocate a local row buffer of the maximum
3334 * size libpng requires and call the relevant processing routine safely.
3337 png_voidp first_row = display->buffer;
3338 ptrdiff_t row_bytes = display->row_stride;
3340 /* The following expression is designed to work correctly whether it gives
3341 * a signed or an unsigned result.
3345 char *ptr = png_voidcast(char*, first_row);
3346 ptr += (image->height-1) * (-row_bytes);
3347 first_row = png_voidcast(png_voidp, ptr);
3350 display->first_row = first_row;
3351 display->row_bytes = row_bytes;
3357 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
3359 display->local_row = row;
3360 result = png_safe_execute(image, png_image_read_and_map, display);
3361 display->local_row = NULL;
3362 png_free(png_ptr, row);
3369 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
3371 while (--passes >= 0)
3373 png_uint_32 y = image->height;
3374 png_bytep row = png_voidcast(png_bytep, display->first_row);
3378 png_read_row(png_ptr, row, NULL);
3387 /* Just the row reading part of png_image_read. */
3389 png_image_read_composite(png_voidp argument)
3391 png_image_read_control *display = png_voidcast(png_image_read_control*,
3393 png_imagep image = display->image;
3394 png_structrp png_ptr = image->opaque->png_ptr;
3397 switch (png_ptr->interlaced)
3399 case PNG_INTERLACE_NONE:
3403 case PNG_INTERLACE_ADAM7:
3404 passes = PNG_INTERLACE_ADAM7_PASSES;
3408 png_error(png_ptr, "unknown interlace type");
3412 png_uint_32 height = image->height;
3413 png_uint_32 width = image->width;
3414 ptrdiff_t step_row = display->row_bytes;
3415 unsigned int channels =
3416 (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
3419 for (pass = 0; pass < passes; ++pass)
3421 unsigned int startx, stepx, stepy;
3424 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3426 /* The row may be empty for a short image: */
3427 if (PNG_PASS_COLS(width, pass) == 0)
3430 startx = PNG_PASS_START_COL(pass) * channels;
3431 stepx = PNG_PASS_COL_OFFSET(pass) * channels;
3432 y = PNG_PASS_START_ROW(pass);
3433 stepy = PNG_PASS_ROW_OFFSET(pass);
3444 for (; y<height; y += stepy)
3446 png_bytep inrow = png_voidcast(png_bytep, display->local_row);
3448 png_const_bytep end_row;
3450 /* Read the row, which is packed: */
3451 png_read_row(png_ptr, inrow, NULL);
3453 outrow = png_voidcast(png_bytep, display->first_row);
3454 outrow += y * step_row;
3455 end_row = outrow + width * channels;
3457 /* Now do the composition on each pixel in this row. */
3459 for (; outrow < end_row; outrow += stepx)
3461 png_byte alpha = inrow[channels];
3463 if (alpha > 0) /* else no change to the output */
3467 for (c=0; c<channels; ++c)
3469 png_uint_32 component = inrow[c];
3471 if (alpha < 255) /* else just use component */
3473 /* This is PNG_OPTIMIZED_ALPHA, the component value
3474 * is a linear 8-bit value. Combine this with the
3475 * current outrow[c] value which is sRGB encoded.
3476 * Arithmetic here is 16-bits to preserve the output
3479 component *= 257*255; /* =65535 */
3480 component += (255-alpha)*png_sRGB_table[outrow[c]];
3482 /* So 'component' is scaled by 255*65535 and is
3483 * therefore appropriate for the sRGB to linear
3486 component = PNG_sRGB_FROM_LINEAR(component);
3489 outrow[c] = (png_byte)component;
3493 inrow += channels+1; /* components and alpha channel */
3502 /* The do_local_background case; called when all the following transforms are to
3509 * This is a work-around for the fact that both the PNG_RGB_TO_GRAY and
3510 * PNG_COMPOSITE code performs gamma correction, so we get double gamma
3511 * correction. The fix-up is to prevent the PNG_COMPOSITE operation from
3512 * happening inside libpng, so this routine sees an 8 or 16-bit gray+alpha
3513 * row and handles the removal or pre-multiplication of the alpha channel.
3516 png_image_read_background(png_voidp argument)
3518 png_image_read_control *display = png_voidcast(png_image_read_control*,
3520 png_imagep image = display->image;
3521 png_structrp png_ptr = image->opaque->png_ptr;
3522 png_inforp info_ptr = image->opaque->info_ptr;
3523 png_uint_32 height = image->height;
3524 png_uint_32 width = image->width;
3527 /* Double check the convoluted logic below. We expect to get here with
3528 * libpng doing rgb to gray and gamma correction but background processing
3529 * left to the png_image_read_background function. The rows libpng produce
3530 * might be 8 or 16-bit but should always have two channels; gray plus alpha.
3532 if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0)
3533 png_error(png_ptr, "lost rgb to gray");
3535 if ((png_ptr->transformations & PNG_COMPOSE) != 0)
3536 png_error(png_ptr, "unexpected compose");
3538 if (png_get_channels(png_ptr, info_ptr) != 2)
3539 png_error(png_ptr, "lost/gained channels");
3541 /* Expect the 8-bit case to always remove the alpha channel */
3542 if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 &&
3543 (image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
3544 png_error(png_ptr, "unexpected 8-bit transformation");
3546 switch (png_ptr->interlaced)
3548 case PNG_INTERLACE_NONE:
3552 case PNG_INTERLACE_ADAM7:
3553 passes = PNG_INTERLACE_ADAM7_PASSES;
3557 png_error(png_ptr, "unknown interlace type");
3560 /* Use direct access to info_ptr here because otherwise the simplified API
3561 * would require PNG_EASY_ACCESS_SUPPORTED (just for this.) Note this is
3562 * checking the value after libpng expansions, not the original value in the
3565 switch (info_ptr->bit_depth)
3568 /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
3569 * to be removed by composing on a background: either the row if
3570 * display->background is NULL or display->background->green if not.
3571 * Unlike the code above ALPHA_OPTIMIZED has *not* been done.
3574 png_bytep first_row = png_voidcast(png_bytep, display->first_row);
3575 ptrdiff_t step_row = display->row_bytes;
3577 for (pass = 0; pass < passes; ++pass)
3579 png_bytep row = png_voidcast(png_bytep, display->first_row);
3580 unsigned int startx, stepx, stepy;
3583 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3585 /* The row may be empty for a short image: */
3586 if (PNG_PASS_COLS(width, pass) == 0)
3589 startx = PNG_PASS_START_COL(pass);
3590 stepx = PNG_PASS_COL_OFFSET(pass);
3591 y = PNG_PASS_START_ROW(pass);
3592 stepy = PNG_PASS_ROW_OFFSET(pass);
3602 if (display->background == NULL)
3604 for (; y<height; y += stepy)
3606 png_bytep inrow = png_voidcast(png_bytep,
3607 display->local_row);
3608 png_bytep outrow = first_row + y * step_row;
3609 png_const_bytep end_row = outrow + width;
3611 /* Read the row, which is packed: */
3612 png_read_row(png_ptr, inrow, NULL);
3614 /* Now do the composition on each pixel in this row. */
3616 for (; outrow < end_row; outrow += stepx)
3618 png_byte alpha = inrow[1];
3620 if (alpha > 0) /* else no change to the output */
3622 png_uint_32 component = inrow[0];
3624 if (alpha < 255) /* else just use component */
3626 /* Since PNG_OPTIMIZED_ALPHA was not set it is
3627 * necessary to invert the sRGB transfer
3628 * function and multiply the alpha out.
3630 component = png_sRGB_table[component] * alpha;
3631 component += png_sRGB_table[outrow[0]] *
3633 component = PNG_sRGB_FROM_LINEAR(component);
3636 outrow[0] = (png_byte)component;
3639 inrow += 2; /* gray and alpha channel */
3644 else /* constant background value */
3646 png_byte background8 = display->background->green;
3647 png_uint_16 background = png_sRGB_table[background8];
3649 for (; y<height; y += stepy)
3651 png_bytep inrow = png_voidcast(png_bytep,
3652 display->local_row);
3653 png_bytep outrow = first_row + y * step_row;
3654 png_const_bytep end_row = outrow + width;
3656 /* Read the row, which is packed: */
3657 png_read_row(png_ptr, inrow, NULL);
3659 /* Now do the composition on each pixel in this row. */
3661 for (; outrow < end_row; outrow += stepx)
3663 png_byte alpha = inrow[1];
3665 if (alpha > 0) /* else use background */
3667 png_uint_32 component = inrow[0];
3669 if (alpha < 255) /* else just use component */
3671 component = png_sRGB_table[component] * alpha;
3672 component += background * (255-alpha);
3673 component = PNG_sRGB_FROM_LINEAR(component);
3676 outrow[0] = (png_byte)component;
3680 outrow[0] = background8;
3682 inrow += 2; /* gray and alpha channel */
3685 row += display->row_bytes;
3693 /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must
3694 * still be done and, maybe, the alpha channel removed. This code also
3695 * handles the alpha-first option.
3698 png_uint_16p first_row = png_voidcast(png_uint_16p,
3699 display->first_row);
3700 /* The division by two is safe because the caller passed in a
3701 * stride which was multiplied by 2 (below) to get row_bytes.
3703 ptrdiff_t step_row = display->row_bytes / 2;
3704 unsigned int preserve_alpha = (image->format &
3705 PNG_FORMAT_FLAG_ALPHA) != 0;
3706 unsigned int outchannels = 1U+preserve_alpha;
3709 # ifdef PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
3710 if (preserve_alpha != 0 &&
3711 (image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
3715 for (pass = 0; pass < passes; ++pass)
3717 unsigned int startx, stepx, stepy;
3720 /* The 'x' start and step are adjusted to output components here.
3722 if (png_ptr->interlaced == PNG_INTERLACE_ADAM7)
3724 /* The row may be empty for a short image: */
3725 if (PNG_PASS_COLS(width, pass) == 0)
3728 startx = PNG_PASS_START_COL(pass) * outchannels;
3729 stepx = PNG_PASS_COL_OFFSET(pass) * outchannels;
3730 y = PNG_PASS_START_ROW(pass);
3731 stepy = PNG_PASS_ROW_OFFSET(pass);
3738 stepx = outchannels;
3742 for (; y<height; y += stepy)
3744 png_const_uint_16p inrow;
3745 png_uint_16p outrow = first_row + y*step_row;
3746 png_uint_16p end_row = outrow + width * outchannels;
3748 /* Read the row, which is packed: */
3749 png_read_row(png_ptr, png_voidcast(png_bytep,
3750 display->local_row), NULL);
3751 inrow = png_voidcast(png_const_uint_16p, display->local_row);
3753 /* Now do the pre-multiplication on each pixel in this row.
3756 for (; outrow < end_row; outrow += stepx)
3758 png_uint_32 component = inrow[0];
3759 png_uint_16 alpha = inrow[1];
3761 if (alpha > 0) /* else 0 */
3763 if (alpha < 65535) /* else just use component */
3774 outrow[swap_alpha] = (png_uint_16)component;
3775 if (preserve_alpha != 0)
3776 outrow[1 ^ swap_alpha] = alpha;
3778 inrow += 2; /* components and alpha channel */
3787 png_error(png_ptr, "unexpected bit depth");
3794 /* The guts of png_image_finish_read as a png_safe_execute callback. */
3796 png_image_read_direct(png_voidp argument)
3798 png_image_read_control *display = png_voidcast(png_image_read_control*,
3800 png_imagep image = display->image;
3801 png_structrp png_ptr = image->opaque->png_ptr;
3802 png_inforp info_ptr = image->opaque->info_ptr;
3804 png_uint_32 format = image->format;
3805 int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0;
3806 int do_local_compose = 0;
3807 int do_local_background = 0; /* to avoid double gamma correction bug */
3810 /* Add transforms to ensure the correct output format is produced then check
3811 * that the required implementation support is there. Always expand; always
3812 * need 8 bits minimum, no palette and expanded tRNS.
3814 png_set_expand(png_ptr);
3816 /* Now check the format to see if it was modified. */
3818 png_uint_32 base_format = png_image_format(png_ptr) &
3819 ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */;
3820 png_uint_32 change = format ^ base_format;
3821 png_fixed_point output_gamma;
3822 int mode; /* alpha mode */
3824 /* Do this first so that we have a record if rgb to gray is happening. */
3825 if ((change & PNG_FORMAT_FLAG_COLOR) != 0)
3827 /* gray<->color transformation required. */
3828 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
3829 png_set_gray_to_rgb(png_ptr);
3833 /* libpng can't do both rgb to gray and
3834 * background/pre-multiplication if there is also significant gamma
3835 * correction, because both operations require linear colors and
3836 * the code only supports one transform doing the gamma correction.
3837 * Handle this by doing the pre-multiplication or background
3838 * operation in this code, if necessary.
3840 * TODO: fix this by rewriting pngrtran.c (!)
3842 * For the moment (given that fixing this in pngrtran.c is an
3843 * enormous change) 'do_local_background' is used to indicate that
3844 * the problem exists.
3846 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3847 do_local_background = 1/*maybe*/;
3849 png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE,
3850 PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT);
3853 change &= ~PNG_FORMAT_FLAG_COLOR;
3856 /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise.
3859 png_fixed_point input_gamma_default;
3861 if ((base_format & PNG_FORMAT_FLAG_LINEAR) != 0 &&
3862 (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0)
3863 input_gamma_default = PNG_GAMMA_LINEAR;
3865 input_gamma_default = PNG_DEFAULT_sRGB;
3867 /* Call png_set_alpha_mode to set the default for the input gamma; the
3868 * output gamma is set by a second call below.
3870 png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default);
3875 /* If there *is* an alpha channel in the input it must be multiplied
3876 * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG.
3878 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3879 mode = PNG_ALPHA_STANDARD; /* associated alpha */
3882 mode = PNG_ALPHA_PNG;
3884 output_gamma = PNG_GAMMA_LINEAR;
3889 mode = PNG_ALPHA_PNG;
3890 output_gamma = PNG_DEFAULT_sRGB;
3893 if ((change & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0)
3895 mode = PNG_ALPHA_OPTIMIZED;
3896 change &= ~PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
3899 /* If 'do_local_background' is set check for the presence of gamma
3900 * correction; this is part of the work-round for the libpng bug
3903 * TODO: fix libpng and remove this.
3905 if (do_local_background != 0)
3907 png_fixed_point gtest;
3909 /* This is 'png_gamma_threshold' from pngrtran.c; the test used for
3910 * gamma correction, the screen gamma hasn't been set on png_struct
3911 * yet; it's set below. png_struct::gamma, however, is set to the
3914 if (png_muldiv(>est, output_gamma, png_ptr->colorspace.gamma,
3915 PNG_FP_1) != 0 && png_gamma_significant(gtest) == 0)
3916 do_local_background = 0;
3918 else if (mode == PNG_ALPHA_STANDARD)
3920 do_local_background = 2/*required*/;
3921 mode = PNG_ALPHA_PNG; /* prevent libpng doing it */
3924 /* else leave as 1 for the checks below */
3927 /* If the bit-depth changes then handle that here. */
3928 if ((change & PNG_FORMAT_FLAG_LINEAR) != 0)
3930 if (linear != 0 /*16-bit output*/)
3931 png_set_expand_16(png_ptr);
3933 else /* 8-bit output */
3934 png_set_scale_16(png_ptr);
3936 change &= ~PNG_FORMAT_FLAG_LINEAR;
3939 /* Now the background/alpha channel changes. */
3940 if ((change & PNG_FORMAT_FLAG_ALPHA) != 0)
3942 /* Removing an alpha channel requires composition for the 8-bit
3943 * formats; for the 16-bit it is already done, above, by the
3944 * pre-multiplication and the channel just needs to be stripped.
3946 if ((base_format & PNG_FORMAT_FLAG_ALPHA) != 0)
3948 /* If RGB->gray is happening the alpha channel must be left and the
3949 * operation completed locally.
3951 * TODO: fix libpng and remove this.
3953 if (do_local_background != 0)
3954 do_local_background = 2/*required*/;
3956 /* 16-bit output: just remove the channel */
3957 else if (linear != 0) /* compose on black (well, pre-multiply) */
3958 png_set_strip_alpha(png_ptr);
3960 /* 8-bit output: do an appropriate compose */
3961 else if (display->background != NULL)
3965 c.index = 0; /*unused*/
3966 c.red = display->background->red;
3967 c.green = display->background->green;
3968 c.blue = display->background->blue;
3969 c.gray = display->background->green;
3971 /* This is always an 8-bit sRGB value, using the 'green' channel
3972 * for gray is much better than calculating the luminance here;
3973 * we can get off-by-one errors in that calculation relative to
3974 * the app expectations and that will show up in transparent
3977 png_set_background_fixed(png_ptr, &c,
3978 PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/,
3979 0/*gamma: not used*/);
3982 else /* compose on row: implemented below. */
3984 do_local_compose = 1;
3985 /* This leaves the alpha channel in the output, so it has to be
3986 * removed by the code below. Set the encoding to the 'OPTIMIZE'
3987 * one so the code only has to hack on the pixels that require
3990 mode = PNG_ALPHA_OPTIMIZED;
3994 else /* output needs an alpha channel */
3996 /* This is tricky because it happens before the swap operation has
3997 * been accomplished; however, the swap does *not* swap the added
3998 * alpha channel (weird API), so it must be added in the correct
4001 png_uint_32 filler; /* opaque filler */
4010 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4011 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4013 where = PNG_FILLER_BEFORE;
4014 change &= ~PNG_FORMAT_FLAG_AFIRST;
4019 where = PNG_FILLER_AFTER;
4021 png_set_add_alpha(png_ptr, filler, where);
4024 /* This stops the (irrelevant) call to swap_alpha below. */
4025 change &= ~PNG_FORMAT_FLAG_ALPHA;
4028 /* Now set the alpha mode correctly; this is always done, even if there is
4029 * no alpha channel in either the input or the output because it correctly
4030 * sets the output gamma.
4032 png_set_alpha_mode_fixed(png_ptr, mode, output_gamma);
4034 # ifdef PNG_FORMAT_BGR_SUPPORTED
4035 if ((change & PNG_FORMAT_FLAG_BGR) != 0)
4037 /* Check only the output format; PNG is never BGR; don't do this if
4038 * the output is gray, but fix up the 'format' value in that case.
4040 if ((format & PNG_FORMAT_FLAG_COLOR) != 0)
4041 png_set_bgr(png_ptr);
4044 format &= ~PNG_FORMAT_FLAG_BGR;
4046 change &= ~PNG_FORMAT_FLAG_BGR;
4050 # ifdef PNG_FORMAT_AFIRST_SUPPORTED
4051 if ((change & PNG_FORMAT_FLAG_AFIRST) != 0)
4053 /* Only relevant if there is an alpha channel - it's particularly
4054 * important to handle this correctly because do_local_compose may
4055 * be set above and then libpng will keep the alpha channel for this
4058 if ((format & PNG_FORMAT_FLAG_ALPHA) != 0)
4060 /* Disable this if doing a local background,
4061 * TODO: remove this when local background is no longer required.
4063 if (do_local_background != 2)
4064 png_set_swap_alpha(png_ptr);
4068 format &= ~PNG_FORMAT_FLAG_AFIRST;
4070 change &= ~PNG_FORMAT_FLAG_AFIRST;
4074 /* If the *output* is 16-bit then we need to check for a byte-swap on this
4079 png_uint_16 le = 0x0001;
4081 if ((*(png_const_bytep) & le) != 0)
4082 png_set_swap(png_ptr);
4085 /* If change is not now 0 some transformation is missing - error out. */
4087 png_error(png_ptr, "png_read_image: unsupported transformation");
4090 PNG_SKIP_CHUNKS(png_ptr);
4092 /* Update the 'info' structure and make sure the result is as required; first
4093 * make sure to turn on the interlace handling if it will be required
4094 * (because it can't be turned on *after* the call to png_read_update_info!)
4096 * TODO: remove the do_local_background fixup below.
4098 if (do_local_compose == 0 && do_local_background != 2)
4099 passes = png_set_interlace_handling(png_ptr);
4101 png_read_update_info(png_ptr, info_ptr);
4104 png_uint_32 info_format = 0;
4106 if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
4107 info_format |= PNG_FORMAT_FLAG_COLOR;
4109 if ((info_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0)
4111 /* do_local_compose removes this channel below. */
4112 if (do_local_compose == 0)
4114 /* do_local_background does the same if required. */
4115 if (do_local_background != 2 ||
4116 (format & PNG_FORMAT_FLAG_ALPHA) != 0)
4117 info_format |= PNG_FORMAT_FLAG_ALPHA;
4121 else if (do_local_compose != 0) /* internal error */
4122 png_error(png_ptr, "png_image_read: alpha channel lost");
4124 if ((format & PNG_FORMAT_FLAG_ASSOCIATED_ALPHA) != 0) {
4125 info_format |= PNG_FORMAT_FLAG_ASSOCIATED_ALPHA;
4128 if (info_ptr->bit_depth == 16)
4129 info_format |= PNG_FORMAT_FLAG_LINEAR;
4131 #ifdef PNG_FORMAT_BGR_SUPPORTED
4132 if ((png_ptr->transformations & PNG_BGR) != 0)
4133 info_format |= PNG_FORMAT_FLAG_BGR;
4136 #ifdef PNG_FORMAT_AFIRST_SUPPORTED
4137 if (do_local_background == 2)
4139 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
4140 info_format |= PNG_FORMAT_FLAG_AFIRST;
4143 if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 ||
4144 ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 &&
4145 (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0))
4147 if (do_local_background == 2)
4148 png_error(png_ptr, "unexpected alpha swap transformation");
4150 info_format |= PNG_FORMAT_FLAG_AFIRST;
4154 /* This is actually an internal error. */
4155 if (info_format != format)
4156 png_error(png_ptr, "png_read_image: invalid transformations");
4159 /* Now read the rows. If do_local_compose is set then it is necessary to use
4160 * a local row buffer. The output will be GA, RGBA or BGRA and must be
4161 * converted to G, RGB or BGR as appropriate. The 'local_row' member of the
4162 * display acts as a flag.
4165 png_voidp first_row = display->buffer;
4166 ptrdiff_t row_bytes = display->row_stride;
4171 /* The following expression is designed to work correctly whether it gives
4172 * a signed or an unsigned result.
4176 char *ptr = png_voidcast(char*, first_row);
4177 ptr += (image->height-1) * (-row_bytes);
4178 first_row = png_voidcast(png_voidp, ptr);
4181 display->first_row = first_row;
4182 display->row_bytes = row_bytes;
4185 if (do_local_compose != 0)
4188 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4190 display->local_row = row;
4191 result = png_safe_execute(image, png_image_read_composite, display);
4192 display->local_row = NULL;
4193 png_free(png_ptr, row);
4198 else if (do_local_background == 2)
4201 png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
4203 display->local_row = row;
4204 result = png_safe_execute(image, png_image_read_background, display);
4205 display->local_row = NULL;
4206 png_free(png_ptr, row);
4213 png_alloc_size_t row_bytes = (png_alloc_size_t)display->row_bytes;
4215 while (--passes >= 0)
4217 png_uint_32 y = image->height;
4218 png_bytep row = png_voidcast(png_bytep, display->first_row);
4222 png_read_row(png_ptr, row, NULL);
4232 png_image_finish_read(png_imagep image, png_const_colorp background,
4233 void *buffer, png_int_32 row_stride, void *colormap)
4235 if (image != NULL && image->version == PNG_IMAGE_VERSION)
4237 /* Check for row_stride overflow. This check is not performed on the
4238 * original PNG format because it may not occur in the output PNG format
4239 * and libpng deals with the issues of reading the original.
4241 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
4243 /* The following checks just the 'row_stride' calculation to ensure it
4244 * fits in a signed 32-bit value. Because channels/components can be
4245 * either 1 or 2 bytes in size the length of a row can still overflow 32
4246 * bits; this is just to verify that the 'row_stride' argument can be
4249 if (image->width <= 0x7fffffffU/channels) /* no overflow */
4252 png_uint_32 png_row_stride = image->width * channels;
4254 if (row_stride == 0)
4255 row_stride = (png_int_32)/*SAFE*/png_row_stride;
4258 check = (png_uint_32)(-row_stride);
4261 check = (png_uint_32)row_stride;
4263 /* This verifies 'check', the absolute value of the actual stride
4264 * passed in and detects overflow in the application calculation (i.e.
4265 * if the app did actually pass in a non-zero 'row_stride'.
4267 if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
4269 /* Now check for overflow of the image buffer calculation; this
4270 * limits the whole image size to 32 bits for API compatibility with
4271 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
4273 * The PNG_IMAGE_BUFFER_SIZE macro is:
4275 * (PNG_IMAGE_PIXEL_COMPONENT_SIZE(fmt)*height*(row_stride))
4277 * And the component size is always 1 or 2, so make sure that the
4278 * number of *bytes* that the application is saying are available
4279 * does actually fit into a 32-bit number.
4281 * NOTE: this will be changed in 1.7 because PNG_IMAGE_BUFFER_SIZE
4282 * will be changed to use png_alloc_size_t; bigger images can be
4283 * accommodated on 64-bit systems.
4285 if (image->height <=
4286 0xffffffffU/PNG_IMAGE_PIXEL_COMPONENT_SIZE(image->format)/check)
4288 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
4289 (image->colormap_entries > 0 && colormap != NULL))
4292 png_image_read_control display;
4294 memset(&display, 0, (sizeof display));
4295 display.image = image;
4296 display.buffer = buffer;
4297 display.row_stride = row_stride;
4298 display.colormap = colormap;
4299 display.background = background;
4300 display.local_row = NULL;
4302 /* Choose the correct 'end' routine; for the color-map case
4303 * all the setup has already been done.
4305 if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4307 png_safe_execute(image,
4308 png_image_read_colormap, &display) &&
4309 png_safe_execute(image,
4310 png_image_read_colormapped, &display);
4314 png_safe_execute(image,
4315 png_image_read_direct, &display);
4317 png_image_free(image);
4322 return png_image_error(image,
4323 "png_image_finish_read[color-map]: no color-map");
4327 return png_image_error(image,
4328 "png_image_finish_read: image too large");
4332 return png_image_error(image,
4333 "png_image_finish_read: invalid argument");
4337 return png_image_error(image,
4338 "png_image_finish_read: row_stride too large");
4341 else if (image != NULL)
4342 return png_image_error(image,
4343 "png_image_finish_read: damaged PNG_IMAGE_VERSION");
4348 #endif /* SIMPLIFIED_READ */