2 /* pngwrite.c - general routines to write 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
15 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
17 #endif /* SIMPLIFIED_WRITE_STDIO */
19 #ifdef PNG_WRITE_SUPPORTED
21 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
22 /* Write out all the unknown chunks for the current given location */
24 write_unknown_chunks(png_structrp png_ptr, png_const_inforp info_ptr,
27 if (info_ptr->unknown_chunks_num != 0)
29 png_const_unknown_chunkp up;
31 png_debug(5, "writing extra chunks");
33 for (up = info_ptr->unknown_chunks;
34 up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
36 if ((up->location & where) != 0)
38 /* If per-chunk unknown chunk handling is enabled use it, otherwise
39 * just write the chunks the application has set.
41 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
42 int keep = png_handle_as_unknown(png_ptr, up->name);
44 /* NOTE: this code is radically different from the read side in the
45 * matter of handling an ancillary unknown chunk. In the read side
46 * the default behavior is to discard it, in the code below the default
47 * behavior is to write it. Critical chunks are, however, only
48 * written if explicitly listed or if the default is set to write all
51 * The default handling is also slightly weird - it is not possible to
52 * stop the writing of all unsafe-to-copy chunks!
54 * TODO: REVIEW: this would seem to be a bug.
56 if (keep != PNG_HANDLE_CHUNK_NEVER &&
57 ((up->name[3] & 0x20) /* safe-to-copy overrides everything */ ||
58 keep == PNG_HANDLE_CHUNK_ALWAYS ||
59 (keep == PNG_HANDLE_CHUNK_AS_DEFAULT &&
60 png_ptr->unknown_default == PNG_HANDLE_CHUNK_ALWAYS)))
63 /* TODO: review, what is wrong with a zero length unknown chunk? */
65 png_warning(png_ptr, "Writing zero-length unknown chunk");
67 png_write_chunk(png_ptr, up->name, up->data, up->size);
72 #endif /* WRITE_UNKNOWN_CHUNKS */
74 /* Writes all the PNG information. This is the suggested way to use the
75 * library. If you have a new chunk to add, make a function to write it,
76 * and put it in the correct location here. If you want the chunk written
77 * after the image data, put it in png_write_end(). I strongly encourage
78 * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
79 * the chunk, as that will keep the code from breaking if you want to just
80 * write a plain PNG file. If you have long comments, I suggest writing
81 * them in png_write_end(), and compressing them.
84 png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
86 png_debug(1, "in png_write_info_before_PLTE");
88 if (png_ptr == NULL || info_ptr == NULL)
91 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
93 /* Write PNG signature */
94 png_write_sig(png_ptr);
96 #ifdef PNG_MNG_FEATURES_SUPPORTED
97 if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
98 png_ptr->mng_features_permitted != 0)
101 "MNG features are not allowed in a PNG datastream");
102 png_ptr->mng_features_permitted = 0;
106 /* Write IHDR information. */
107 png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
108 info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
109 info_ptr->filter_type,
110 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
111 info_ptr->interlace_type
117 /* The rest of these check to see if the valid field has the appropriate
118 * flag set, and if it does, writes the chunk.
120 * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
121 * the chunks will be written if the WRITE routine is there and
122 * information * is available in the COLORSPACE. (See
123 * png_colorspace_sync_info in png.c for where the valid flags get set.)
125 * Under certain circumstances the colorspace can be invalidated without
126 * syncing the info_struct 'valid' flags; this happens if libpng detects
127 * an error and calls png_error while the color space is being set, yet
128 * the application continues writing the PNG. So check the 'invalid'
131 #ifdef PNG_WRITE_APNG_SUPPORTED
132 if (info_ptr->valid & PNG_INFO_acTL)
133 png_write_acTL(png_ptr, info_ptr->num_frames, info_ptr->num_plays);
135 #ifdef PNG_GAMMA_SUPPORTED
136 # ifdef PNG_WRITE_gAMA_SUPPORTED
137 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
138 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_gAMA) != 0 &&
139 (info_ptr->valid & PNG_INFO_gAMA) != 0)
140 png_write_gAMA_fixed(png_ptr, info_ptr->colorspace.gamma);
144 #ifdef PNG_COLORSPACE_SUPPORTED
145 /* Write only one of sRGB or an ICC profile. If a profile was supplied
146 * and it matches one of the known sRGB ones issue a warning.
148 # ifdef PNG_WRITE_iCCP_SUPPORTED
149 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
150 (info_ptr->valid & PNG_INFO_iCCP) != 0)
152 # ifdef PNG_WRITE_sRGB_SUPPORTED
153 if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
154 png_app_warning(png_ptr,
155 "profile matches sRGB but writing iCCP instead");
158 png_write_iCCP(png_ptr, info_ptr->iccp_name,
159 info_ptr->iccp_profile);
161 # ifdef PNG_WRITE_sRGB_SUPPORTED
166 # ifdef PNG_WRITE_sRGB_SUPPORTED
167 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
168 (info_ptr->valid & PNG_INFO_sRGB) != 0)
169 png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
170 # endif /* WRITE_sRGB */
171 #endif /* COLORSPACE */
173 #ifdef PNG_WRITE_sBIT_SUPPORTED
174 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
175 png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
178 #ifdef PNG_COLORSPACE_SUPPORTED
179 # ifdef PNG_WRITE_cHRM_SUPPORTED
180 if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
181 (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
182 (info_ptr->valid & PNG_INFO_cHRM) != 0)
183 png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
187 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
188 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
191 png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
196 png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
198 #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
202 png_debug(1, "in png_write_info");
204 if (png_ptr == NULL || info_ptr == NULL)
207 png_write_info_before_PLTE(png_ptr, info_ptr);
209 if ((info_ptr->valid & PNG_INFO_PLTE) != 0)
210 png_write_PLTE(png_ptr, info_ptr->palette,
211 (png_uint_32)info_ptr->num_palette);
213 else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
214 png_error(png_ptr, "Valid palette required for paletted images");
216 #ifdef PNG_WRITE_tRNS_SUPPORTED
217 if ((info_ptr->valid & PNG_INFO_tRNS) !=0)
219 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
220 /* Invert the alpha channel (in tRNS) */
221 if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
222 info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
226 jend = info_ptr->num_trans;
227 if (jend > PNG_MAX_PALETTE_LENGTH)
228 jend = PNG_MAX_PALETTE_LENGTH;
230 for (j = 0; j<jend; ++j)
231 info_ptr->trans_alpha[j] =
232 (png_byte)(255 - info_ptr->trans_alpha[j]);
235 png_write_tRNS(png_ptr, info_ptr->trans_alpha, &(info_ptr->trans_color),
236 info_ptr->num_trans, info_ptr->color_type);
239 #ifdef PNG_WRITE_bKGD_SUPPORTED
240 if ((info_ptr->valid & PNG_INFO_bKGD) != 0)
241 png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
244 #ifdef PNG_WRITE_eXIf_SUPPORTED
245 if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
246 png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
249 #ifdef PNG_WRITE_hIST_SUPPORTED
250 if ((info_ptr->valid & PNG_INFO_hIST) != 0)
251 png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
254 #ifdef PNG_WRITE_oFFs_SUPPORTED
255 if ((info_ptr->valid & PNG_INFO_oFFs) != 0)
256 png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
257 info_ptr->offset_unit_type);
260 #ifdef PNG_WRITE_pCAL_SUPPORTED
261 if ((info_ptr->valid & PNG_INFO_pCAL) != 0)
262 png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
263 info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
264 info_ptr->pcal_units, info_ptr->pcal_params);
267 #ifdef PNG_WRITE_sCAL_SUPPORTED
268 if ((info_ptr->valid & PNG_INFO_sCAL) != 0)
269 png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
270 info_ptr->scal_s_width, info_ptr->scal_s_height);
273 #ifdef PNG_WRITE_pHYs_SUPPORTED
274 if ((info_ptr->valid & PNG_INFO_pHYs) != 0)
275 png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
276 info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
279 #ifdef PNG_WRITE_tIME_SUPPORTED
280 if ((info_ptr->valid & PNG_INFO_tIME) != 0)
282 png_write_tIME(png_ptr, &(info_ptr->mod_time));
283 png_ptr->mode |= PNG_WROTE_tIME;
287 #ifdef PNG_WRITE_sPLT_SUPPORTED
288 if ((info_ptr->valid & PNG_INFO_sPLT) != 0)
289 for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
290 png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
293 #ifdef PNG_WRITE_TEXT_SUPPORTED
294 /* Check to see if we need to write text chunks */
295 for (i = 0; i < info_ptr->num_text; i++)
297 png_debug2(2, "Writing header text chunk %d, type %d", i,
298 info_ptr->text[i].compression);
299 /* An internationalized chunk? */
300 if (info_ptr->text[i].compression > 0)
302 #ifdef PNG_WRITE_iTXt_SUPPORTED
303 /* Write international chunk */
304 png_write_iTXt(png_ptr,
305 info_ptr->text[i].compression,
306 info_ptr->text[i].key,
307 info_ptr->text[i].lang,
308 info_ptr->text[i].lang_key,
309 info_ptr->text[i].text);
310 /* Mark this chunk as written */
311 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
312 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
314 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
316 png_warning(png_ptr, "Unable to write international text");
320 /* If we want a compressed text chunk */
321 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
323 #ifdef PNG_WRITE_zTXt_SUPPORTED
324 /* Write compressed chunk */
325 png_write_zTXt(png_ptr, info_ptr->text[i].key,
326 info_ptr->text[i].text, info_ptr->text[i].compression);
327 /* Mark this chunk as written */
328 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
330 png_warning(png_ptr, "Unable to write compressed text");
334 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
336 #ifdef PNG_WRITE_tEXt_SUPPORTED
337 /* Write uncompressed chunk */
338 png_write_tEXt(png_ptr, info_ptr->text[i].key,
339 info_ptr->text[i].text,
341 /* Mark this chunk as written */
342 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
345 png_warning(png_ptr, "Unable to write uncompressed text");
351 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
352 write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_PLTE);
356 /* Writes the end of the PNG file. If you don't want to write comments or
357 * time information, you can pass NULL for info. If you already wrote these
358 * in png_write_info(), do not write them again here. If you have long
359 * comments, I suggest writing them here, and compressing them.
362 png_write_end(png_structrp png_ptr, png_inforp info_ptr)
364 png_debug(1, "in png_write_end");
369 if ((png_ptr->mode & PNG_HAVE_IDAT) == 0)
370 png_error(png_ptr, "No IDATs written into file");
372 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
373 if (png_ptr->num_palette_max > png_ptr->num_palette)
374 png_benign_error(png_ptr, "Wrote palette index exceeding num_palette");
377 #ifdef PNG_WRITE_APNG_SUPPORTED
378 if (png_ptr->num_frames_written != png_ptr->num_frames_to_write)
379 png_error(png_ptr, "Not enough frames written");
382 /* See if user wants us to write information chunks */
383 if (info_ptr != NULL)
385 #ifdef PNG_WRITE_TEXT_SUPPORTED
386 int i; /* local index variable */
388 #ifdef PNG_WRITE_tIME_SUPPORTED
389 /* Check to see if user has supplied a time chunk */
390 if ((info_ptr->valid & PNG_INFO_tIME) != 0 &&
391 (png_ptr->mode & PNG_WROTE_tIME) == 0)
392 png_write_tIME(png_ptr, &(info_ptr->mod_time));
395 #ifdef PNG_WRITE_TEXT_SUPPORTED
396 /* Loop through comment chunks */
397 for (i = 0; i < info_ptr->num_text; i++)
399 png_debug2(2, "Writing trailer text chunk %d, type %d", i,
400 info_ptr->text[i].compression);
401 /* An internationalized chunk? */
402 if (info_ptr->text[i].compression > 0)
404 #ifdef PNG_WRITE_iTXt_SUPPORTED
405 /* Write international chunk */
406 png_write_iTXt(png_ptr,
407 info_ptr->text[i].compression,
408 info_ptr->text[i].key,
409 info_ptr->text[i].lang,
410 info_ptr->text[i].lang_key,
411 info_ptr->text[i].text);
412 /* Mark this chunk as written */
413 if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
414 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
416 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
418 png_warning(png_ptr, "Unable to write international text");
422 else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
424 #ifdef PNG_WRITE_zTXt_SUPPORTED
425 /* Write compressed chunk */
426 png_write_zTXt(png_ptr, info_ptr->text[i].key,
427 info_ptr->text[i].text, info_ptr->text[i].compression);
428 /* Mark this chunk as written */
429 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
431 png_warning(png_ptr, "Unable to write compressed text");
435 else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
437 #ifdef PNG_WRITE_tEXt_SUPPORTED
438 /* Write uncompressed chunk */
439 png_write_tEXt(png_ptr, info_ptr->text[i].key,
440 info_ptr->text[i].text, 0);
441 /* Mark this chunk as written */
442 info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
444 png_warning(png_ptr, "Unable to write uncompressed text");
450 #ifdef PNG_WRITE_eXIf_SUPPORTED
451 if ((info_ptr->valid & PNG_INFO_eXIf) != 0)
452 png_write_eXIf(png_ptr, info_ptr->exif, info_ptr->num_exif);
455 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
456 write_unknown_chunks(png_ptr, info_ptr, PNG_AFTER_IDAT);
460 png_ptr->mode |= PNG_AFTER_IDAT;
462 /* Write end of PNG file */
463 png_write_IEND(png_ptr);
465 /* This flush, added in libpng-1.0.8, removed from libpng-1.0.9beta03,
466 * and restored again in libpng-1.2.30, may cause some applications that
467 * do not set png_ptr->output_flush_fn to crash. If your application
468 * experiences a problem, please try building libpng with
469 * PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED defined, and report the event to
470 * png-mng-implement at lists.sf.net .
472 #ifdef PNG_WRITE_FLUSH_SUPPORTED
473 # ifdef PNG_WRITE_FLUSH_AFTER_IEND_SUPPORTED
479 #ifdef PNG_CONVERT_tIME_SUPPORTED
481 png_convert_from_struct_tm(png_timep ptime, const struct tm * ttime)
483 png_debug(1, "in png_convert_from_struct_tm");
485 ptime->year = (png_uint_16)(1900 + ttime->tm_year);
486 ptime->month = (png_byte)(ttime->tm_mon + 1);
487 ptime->day = (png_byte)ttime->tm_mday;
488 ptime->hour = (png_byte)ttime->tm_hour;
489 ptime->minute = (png_byte)ttime->tm_min;
490 ptime->second = (png_byte)ttime->tm_sec;
494 png_convert_from_time_t(png_timep ptime, time_t ttime)
498 png_debug(1, "in png_convert_from_time_t");
500 tbuf = gmtime(&ttime);
501 png_convert_from_struct_tm(ptime, tbuf);
505 /* Initialize png_ptr structure, and allocate any memory needed */
506 PNG_FUNCTION(png_structp,PNGAPI
507 png_create_write_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
508 png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED)
510 #ifndef PNG_USER_MEM_SUPPORTED
511 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
512 error_fn, warn_fn, NULL, NULL, NULL);
514 return png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
515 warn_fn, NULL, NULL, NULL);
518 /* Alternate initialize png_ptr structure, and allocate any memory needed */
519 PNG_FUNCTION(png_structp,PNGAPI
520 png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
521 png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
522 png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED)
524 png_structrp png_ptr = png_create_png_struct(user_png_ver, error_ptr,
525 error_fn, warn_fn, mem_ptr, malloc_fn, free_fn);
526 #endif /* USER_MEM */
529 /* Set the zlib control values to defaults; they can be overridden by the
530 * application after the struct has been created.
532 png_ptr->zbuffer_size = PNG_ZBUF_SIZE;
534 /* The 'zlib_strategy' setting is irrelevant because png_default_claim in
535 * pngwutil.c defaults it according to whether or not filters will be
536 * used, and ignores this setting.
538 png_ptr->zlib_strategy = PNG_Z_DEFAULT_STRATEGY;
539 png_ptr->zlib_level = PNG_Z_DEFAULT_COMPRESSION;
540 png_ptr->zlib_mem_level = 8;
541 png_ptr->zlib_window_bits = 15;
542 png_ptr->zlib_method = 8;
544 #ifdef PNG_WRITE_COMPRESSED_TEXT_SUPPORTED
545 png_ptr->zlib_text_strategy = PNG_TEXT_Z_DEFAULT_STRATEGY;
546 png_ptr->zlib_text_level = PNG_TEXT_Z_DEFAULT_COMPRESSION;
547 png_ptr->zlib_text_mem_level = 8;
548 png_ptr->zlib_text_window_bits = 15;
549 png_ptr->zlib_text_method = 8;
550 #endif /* WRITE_COMPRESSED_TEXT */
552 /* This is a highly dubious configuration option; by default it is off,
553 * but it may be appropriate for private builds that are testing
554 * extensions not conformant to the current specification, or of
555 * applications that must not fail to write at all costs!
557 #ifdef PNG_BENIGN_WRITE_ERRORS_SUPPORTED
558 /* In stable builds only warn if an application error can be completely
561 png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN;
564 /* App warnings are warnings in release (or release candidate) builds but
565 * are errors during development.
567 #if PNG_RELEASE_BUILD
568 png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
571 /* TODO: delay this, it can be done in png_init_io() (if the app doesn't
572 * do it itself) avoiding setting the default function if it is not
575 png_set_write_fn(png_ptr, NULL, NULL, NULL);
582 /* Write a few rows of image data. If the image is interlaced,
583 * either you will have to write the 7 sub images, or, if you
584 * have called png_set_interlace_handling(), you will have to
585 * "write" the image seven times.
588 png_write_rows(png_structrp png_ptr, png_bytepp row,
589 png_uint_32 num_rows)
591 png_uint_32 i; /* row counter */
592 png_bytepp rp; /* row pointer */
594 png_debug(1, "in png_write_rows");
599 /* Loop through the rows */
600 for (i = 0, rp = row; i < num_rows; i++, rp++)
602 png_write_row(png_ptr, *rp);
606 /* Write the image. You only need to call this function once, even
607 * if you are writing an interlaced image.
610 png_write_image(png_structrp png_ptr, png_bytepp image)
612 png_uint_32 i; /* row index */
613 int pass, num_pass; /* pass variables */
614 png_bytepp rp; /* points to current row */
619 png_debug(1, "in png_write_image");
621 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
622 /* Initialize interlace handling. If image is not interlaced,
623 * this will set pass to 1
625 num_pass = png_set_interlace_handling(png_ptr);
629 /* Loop through passes */
630 for (pass = 0; pass < num_pass; pass++)
632 /* Loop through image */
633 for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
635 png_write_row(png_ptr, *rp);
640 #ifdef PNG_MNG_FEATURES_SUPPORTED
641 /* Performs intrapixel differencing */
643 png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
645 png_debug(1, "in png_do_write_intrapixel");
647 if ((row_info->color_type & PNG_COLOR_MASK_COLOR) != 0)
650 png_uint_32 row_width = row_info->width;
651 if (row_info->bit_depth == 8)
656 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
659 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
665 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
667 *(rp) = (png_byte)(*rp - *(rp + 1));
668 *(rp + 2) = (png_byte)(*(rp + 2) - *(rp + 1));
672 #ifdef PNG_WRITE_16BIT_SUPPORTED
673 else if (row_info->bit_depth == 16)
678 if (row_info->color_type == PNG_COLOR_TYPE_RGB)
681 else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
687 for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
689 png_uint_32 s0 = (png_uint_32)(*(rp ) << 8) | *(rp + 1);
690 png_uint_32 s1 = (png_uint_32)(*(rp + 2) << 8) | *(rp + 3);
691 png_uint_32 s2 = (png_uint_32)(*(rp + 4) << 8) | *(rp + 5);
692 png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
693 png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
694 *(rp ) = (png_byte)(red >> 8);
695 *(rp + 1) = (png_byte)red;
696 *(rp + 4) = (png_byte)(blue >> 8);
697 *(rp + 5) = (png_byte)blue;
700 #endif /* WRITE_16BIT */
703 #endif /* MNG_FEATURES */
705 /* Called by user to write a row of image data */
707 png_write_row(png_structrp png_ptr, png_const_bytep row)
709 /* 1.5.6: moved from png_struct to be a local structure: */
710 png_row_info row_info;
715 png_debug2(1, "in png_write_row (row %u, pass %d)",
716 png_ptr->row_number, png_ptr->pass);
718 /* Initialize transformations and other stuff if first time */
719 if (png_ptr->row_number == 0 && png_ptr->pass == 0)
721 /* Make sure we wrote the header info */
722 if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
724 "png_write_info was never called before png_write_row");
726 /* Check for transforms that have been set but were defined out */
727 #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
728 if ((png_ptr->transformations & PNG_INVERT_MONO) != 0)
729 png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined");
732 #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
733 if ((png_ptr->transformations & PNG_FILLER) != 0)
734 png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined");
736 #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \
737 defined(PNG_READ_PACKSWAP_SUPPORTED)
738 if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
740 "PNG_WRITE_PACKSWAP_SUPPORTED is not defined");
743 #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
744 if ((png_ptr->transformations & PNG_PACK) != 0)
745 png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined");
748 #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
749 if ((png_ptr->transformations & PNG_SHIFT) != 0)
750 png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined");
753 #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
754 if ((png_ptr->transformations & PNG_BGR) != 0)
755 png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined");
758 #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
759 if ((png_ptr->transformations & PNG_SWAP_BYTES) != 0)
760 png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined");
763 png_write_start_row(png_ptr);
766 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
767 /* If interlaced and not interested in row, return */
768 if (png_ptr->interlaced != 0 &&
769 (png_ptr->transformations & PNG_INTERLACE) != 0)
771 switch (png_ptr->pass)
774 if ((png_ptr->row_number & 0x07) != 0)
776 png_write_finish_row(png_ptr);
782 if ((png_ptr->row_number & 0x07) != 0 || png_ptr->width < 5)
784 png_write_finish_row(png_ptr);
790 if ((png_ptr->row_number & 0x07) != 4)
792 png_write_finish_row(png_ptr);
798 if ((png_ptr->row_number & 0x03) != 0 || png_ptr->width < 3)
800 png_write_finish_row(png_ptr);
806 if ((png_ptr->row_number & 0x03) != 2)
808 png_write_finish_row(png_ptr);
814 if ((png_ptr->row_number & 0x01) != 0 || png_ptr->width < 2)
816 png_write_finish_row(png_ptr);
822 if ((png_ptr->row_number & 0x01) == 0)
824 png_write_finish_row(png_ptr);
829 default: /* error: ignore it */
835 /* Set up row info for transformations */
836 row_info.color_type = png_ptr->color_type;
837 row_info.width = png_ptr->usr_width;
838 row_info.channels = png_ptr->usr_channels;
839 row_info.bit_depth = png_ptr->usr_bit_depth;
840 row_info.pixel_depth = (png_byte)(row_info.bit_depth * row_info.channels);
841 row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width);
843 png_debug1(3, "row_info->color_type = %d", row_info.color_type);
844 png_debug1(3, "row_info->width = %u", row_info.width);
845 png_debug1(3, "row_info->channels = %d", row_info.channels);
846 png_debug1(3, "row_info->bit_depth = %d", row_info.bit_depth);
847 png_debug1(3, "row_info->pixel_depth = %d", row_info.pixel_depth);
848 png_debug1(3, "row_info->rowbytes = %lu", (unsigned long)row_info.rowbytes);
850 /* Copy user's row into buffer, leaving room for filter byte. */
851 memcpy(png_ptr->row_buf + 1, row, row_info.rowbytes);
853 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
854 /* Handle interlacing */
855 if (png_ptr->interlaced && png_ptr->pass < 6 &&
856 (png_ptr->transformations & PNG_INTERLACE) != 0)
858 png_do_write_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass);
859 /* This should always get caught above, but still ... */
860 if (row_info.width == 0)
862 png_write_finish_row(png_ptr);
868 #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
869 /* Handle other transformations */
870 if (png_ptr->transformations != 0)
871 png_do_write_transformations(png_ptr, &row_info);
874 /* At this point the row_info pixel depth must match the 'transformed' depth,
875 * which is also the output depth.
877 if (row_info.pixel_depth != png_ptr->pixel_depth ||
878 row_info.pixel_depth != png_ptr->transformed_pixel_depth)
879 png_error(png_ptr, "internal write transform logic error");
881 #ifdef PNG_MNG_FEATURES_SUPPORTED
882 /* Write filter_method 64 (intrapixel differencing) only if
883 * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
884 * 2. Libpng did not write a PNG signature (this filter_method is only
885 * used in PNG datastreams that are embedded in MNG datastreams) and
886 * 3. The application called png_permit_mng_features with a mask that
887 * included PNG_FLAG_MNG_FILTER_64 and
888 * 4. The filter_method is 64 and
889 * 5. The color_type is RGB or RGBA
891 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
892 (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
894 /* Intrapixel differencing */
895 png_do_write_intrapixel(&row_info, png_ptr->row_buf + 1);
899 /* Added at libpng-1.5.10 */
900 #ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
901 /* Check for out-of-range palette index */
902 if (row_info.color_type == PNG_COLOR_TYPE_PALETTE &&
903 png_ptr->num_palette_max >= 0)
904 png_do_check_palette_indexes(png_ptr, &row_info);
907 /* Find a filter if necessary, filter the row and write it out. */
908 png_write_find_filter(png_ptr, &row_info);
910 if (png_ptr->write_row_fn != NULL)
911 (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
914 #ifdef PNG_WRITE_FLUSH_SUPPORTED
915 /* Set the automatic flush interval or 0 to turn flushing off */
917 png_set_flush(png_structrp png_ptr, int nrows)
919 png_debug(1, "in png_set_flush");
924 png_ptr->flush_dist = (nrows < 0 ? 0 : (png_uint_32)nrows);
927 /* Flush the current output buffers now */
929 png_write_flush(png_structrp png_ptr)
931 png_debug(1, "in png_write_flush");
936 /* We have already written out all of the data */
937 if (png_ptr->row_number >= png_ptr->num_rows)
940 png_compress_IDAT(png_ptr, NULL, 0, Z_SYNC_FLUSH);
941 png_ptr->flush_rows = 0;
944 #endif /* WRITE_FLUSH */
946 /* Free any memory used in png_ptr struct without freeing the struct itself. */
948 png_write_destroy(png_structrp png_ptr)
950 png_debug(1, "in png_write_destroy");
952 /* Free any memory zlib uses */
953 if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0)
954 deflateEnd(&png_ptr->zstream);
956 /* Free our memory. png_free checks NULL for us. */
957 png_free_buffer_list(png_ptr, &png_ptr->zbuffer_list);
958 png_free(png_ptr, png_ptr->row_buf);
959 png_ptr->row_buf = NULL;
960 #ifdef PNG_WRITE_FILTER_SUPPORTED
961 png_free(png_ptr, png_ptr->prev_row);
962 png_free(png_ptr, png_ptr->try_row);
963 png_free(png_ptr, png_ptr->tst_row);
964 png_ptr->prev_row = NULL;
965 png_ptr->try_row = NULL;
966 png_ptr->tst_row = NULL;
969 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
970 png_free(png_ptr, png_ptr->chunk_list);
971 png_ptr->chunk_list = NULL;
974 /* The error handling and memory handling information is left intact at this
975 * point: the jmp_buf may still have to be freed. See png_destroy_png_struct
976 * for how this happens.
980 /* Free all memory used by the write.
981 * In libpng 1.6.0 this API changed quietly to no longer accept a NULL value for
982 * *png_ptr_ptr. Prior to 1.6.0 it would accept such a value and it would free
983 * the passed in info_structs but it would quietly fail to free any of the data
984 * inside them. In 1.6.0 it quietly does nothing (it has to be quiet because it
988 png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
990 png_debug(1, "in png_destroy_write_struct");
992 if (png_ptr_ptr != NULL)
994 png_structrp png_ptr = *png_ptr_ptr;
996 if (png_ptr != NULL) /* added in libpng 1.6.0 */
998 png_destroy_info_struct(png_ptr, info_ptr_ptr);
1000 *png_ptr_ptr = NULL;
1001 png_write_destroy(png_ptr);
1002 png_destroy_png_struct(png_ptr);
1007 /* Allow the application to select one or more row filters to use. */
1009 png_set_filter(png_structrp png_ptr, int method, int filters)
1011 png_debug(1, "in png_set_filter");
1013 if (png_ptr == NULL)
1016 #ifdef PNG_MNG_FEATURES_SUPPORTED
1017 if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) != 0 &&
1018 (method == PNG_INTRAPIXEL_DIFFERENCING))
1019 method = PNG_FILTER_TYPE_BASE;
1022 if (method == PNG_FILTER_TYPE_BASE)
1024 switch (filters & (PNG_ALL_FILTERS | 0x07))
1026 #ifdef PNG_WRITE_FILTER_SUPPORTED
1029 case 7: png_app_error(png_ptr, "Unknown row filter for method 0");
1030 #endif /* WRITE_FILTER */
1033 /* 'switch ~ case' is dead code.
1034 * If filters is #PNG_FILTER_VALUE_NONE, #PNG_FILTER_VALUE_SUB ...,
1035 * filter flag will be assigned to 'png_ptr->do_filter'. But
1036 * 'png_ptr->do_filter' is overwritten as 'filters' at below code.
1037 * Issue code(#1155) is 'png_ptr->do_filter = (png_byte)filters;'.
1038 * So the result of 'switch ~ case' has been lost at the line.
1039 * To keep the value of 'switch ~ case', we fixed it to apply
1040 * the result into 'filters'.
1041 * It will be updated into 'png_ptr->do_filter' at #1155 line.
1043 case PNG_FILTER_VALUE_NONE:
1044 filters = PNG_FILTER_NONE; break;
1046 case PNG_FILTER_VALUE_NONE:
1047 png_ptr->do_filter = PNG_FILTER_NONE; break;
1048 #endif /* __TIZEN__ */
1050 #ifdef PNG_WRITE_FILTER_SUPPORTED
1052 case PNG_FILTER_VALUE_SUB:
1053 filters = PNG_FILTER_SUB; break;
1055 case PNG_FILTER_VALUE_UP:
1056 filters = PNG_FILTER_UP; break;
1058 case PNG_FILTER_VALUE_AVG:
1059 filters = PNG_FILTER_AVG; break;
1061 case PNG_FILTER_VALUE_PAETH:
1062 filters = PNG_FILTER_PAETH; break;
1064 case PNG_FILTER_VALUE_SUB:
1065 png_ptr->do_filter = PNG_FILTER_SUB; break;
1067 case PNG_FILTER_VALUE_UP:
1068 png_ptr->do_filter = PNG_FILTER_UP; break;
1070 case PNG_FILTER_VALUE_AVG:
1071 png_ptr->do_filter = PNG_FILTER_AVG; break;
1073 case PNG_FILTER_VALUE_PAETH:
1074 png_ptr->do_filter = PNG_FILTER_PAETH; break;
1075 #endif /* __TIZEN__ */
1077 png_ptr->do_filter = (png_byte)filters; break;
1080 png_app_error(png_ptr, "Unknown row filter for method 0");
1081 #endif /* WRITE_FILTER */
1084 #ifdef PNG_WRITE_FILTER_SUPPORTED
1085 /* If we have allocated the row_buf, this means we have already started
1086 * with the image and we should have allocated all of the filter buffers
1087 * that have been selected. If prev_row isn't already allocated, then
1088 * it is too late to start using the filters that need it, since we
1089 * will be missing the data in the previous row. If an application
1090 * wants to start and stop using particular filters during compression,
1091 * it should start out with all of the filters, and then remove them
1092 * or add them back after the start of compression.
1094 * NOTE: this is a nasty constraint on the code, because it means that the
1095 * prev_row buffer must be maintained even if there are currently no
1096 * 'prev_row' requiring filters active.
1098 if (png_ptr->row_buf != NULL)
1101 png_alloc_size_t buf_size;
1103 /* Repeat the checks in png_write_start_row; 1 pixel high or wide
1104 * images cannot benefit from certain filters. If this isn't done here
1105 * the check below will fire on 1 pixel high images.
1107 if (png_ptr->height == 1)
1108 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1110 if (png_ptr->width == 1)
1111 filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1113 if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
1114 && png_ptr->prev_row == NULL)
1116 /* This is the error case, however it is benign - the previous row
1117 * is not available so the filter can't be used. Just warn here.
1119 png_app_warning(png_ptr,
1120 "png_set_filter: UP/AVG/PAETH cannot be added after start");
1121 filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
1126 if (filters & PNG_FILTER_SUB)
1129 if (filters & PNG_FILTER_UP)
1132 if (filters & PNG_FILTER_AVG)
1135 if (filters & PNG_FILTER_PAETH)
1138 /* Allocate needed row buffers if they have not already been
1141 buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
1142 png_ptr->width) + 1;
1144 if (png_ptr->try_row == NULL)
1145 png_ptr->try_row = png_voidcast(png_bytep,
1146 png_malloc(png_ptr, buf_size));
1148 if (num_filters > 1)
1150 if (png_ptr->tst_row == NULL)
1151 png_ptr->tst_row = png_voidcast(png_bytep,
1152 png_malloc(png_ptr, buf_size));
1155 png_ptr->do_filter = (png_byte)filters;
1159 png_error(png_ptr, "Unknown custom filter method");
1162 #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
1163 /* Provide floating and fixed point APIs */
1164 #ifdef PNG_FLOATING_POINT_SUPPORTED
1166 png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
1167 int num_weights, png_const_doublep filter_weights,
1168 png_const_doublep filter_costs)
1171 PNG_UNUSED(heuristic_method)
1172 PNG_UNUSED(num_weights)
1173 PNG_UNUSED(filter_weights)
1174 PNG_UNUSED(filter_costs)
1176 #endif /* FLOATING_POINT */
1178 #ifdef PNG_FIXED_POINT_SUPPORTED
1180 png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
1181 int num_weights, png_const_fixed_point_p filter_weights,
1182 png_const_fixed_point_p filter_costs)
1185 PNG_UNUSED(heuristic_method)
1186 PNG_UNUSED(num_weights)
1187 PNG_UNUSED(filter_weights)
1188 PNG_UNUSED(filter_costs)
1190 #endif /* FIXED_POINT */
1191 #endif /* WRITE_WEIGHTED_FILTER */
1193 #ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
1195 png_set_compression_level(png_structrp png_ptr, int level)
1197 png_debug(1, "in png_set_compression_level");
1199 if (png_ptr == NULL)
1202 png_ptr->zlib_level = level;
1206 png_set_compression_mem_level(png_structrp png_ptr, int mem_level)
1208 png_debug(1, "in png_set_compression_mem_level");
1210 if (png_ptr == NULL)
1213 png_ptr->zlib_mem_level = mem_level;
1217 png_set_compression_strategy(png_structrp png_ptr, int strategy)
1219 png_debug(1, "in png_set_compression_strategy");
1221 if (png_ptr == NULL)
1224 /* The flag setting here prevents the libpng dynamic selection of strategy.
1226 png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
1227 png_ptr->zlib_strategy = strategy;
1230 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1231 * smaller value of window_bits if it can do so safely.
1234 png_set_compression_window_bits(png_structrp png_ptr, int window_bits)
1236 if (png_ptr == NULL)
1239 /* Prior to 1.6.0 this would warn but then set the window_bits value. This
1240 * meant that negative window bits values could be selected that would cause
1241 * libpng to write a non-standard PNG file with raw deflate or gzip
1242 * compressed IDAT or ancillary chunks. Such files can be read and there is
1243 * no warning on read, so this seems like a very bad idea.
1245 if (window_bits > 15)
1247 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1251 else if (window_bits < 8)
1253 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1257 png_ptr->zlib_window_bits = window_bits;
1261 png_set_compression_method(png_structrp png_ptr, int method)
1263 png_debug(1, "in png_set_compression_method");
1265 if (png_ptr == NULL)
1268 /* This would produce an invalid PNG file if it worked, but it doesn't and
1269 * deflate will fault it, so it is harmless to just warn here.
1272 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1274 png_ptr->zlib_method = method;
1276 #endif /* WRITE_CUSTOMIZE_COMPRESSION */
1278 /* The following were added to libpng-1.5.4 */
1279 #ifdef PNG_WRITE_CUSTOMIZE_ZTXT_COMPRESSION_SUPPORTED
1281 png_set_text_compression_level(png_structrp png_ptr, int level)
1283 png_debug(1, "in png_set_text_compression_level");
1285 if (png_ptr == NULL)
1288 png_ptr->zlib_text_level = level;
1292 png_set_text_compression_mem_level(png_structrp png_ptr, int mem_level)
1294 png_debug(1, "in png_set_text_compression_mem_level");
1296 if (png_ptr == NULL)
1299 png_ptr->zlib_text_mem_level = mem_level;
1303 png_set_text_compression_strategy(png_structrp png_ptr, int strategy)
1305 png_debug(1, "in png_set_text_compression_strategy");
1307 if (png_ptr == NULL)
1310 png_ptr->zlib_text_strategy = strategy;
1313 /* If PNG_WRITE_OPTIMIZE_CMF_SUPPORTED is defined, libpng will use a
1314 * smaller value of window_bits if it can do so safely.
1317 png_set_text_compression_window_bits(png_structrp png_ptr, int window_bits)
1319 if (png_ptr == NULL)
1322 if (window_bits > 15)
1324 png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
1328 else if (window_bits < 8)
1330 png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
1334 png_ptr->zlib_text_window_bits = window_bits;
1338 png_set_text_compression_method(png_structrp png_ptr, int method)
1340 png_debug(1, "in png_set_text_compression_method");
1342 if (png_ptr == NULL)
1346 png_warning(png_ptr, "Only compression method 8 is supported by PNG");
1348 png_ptr->zlib_text_method = method;
1350 #endif /* WRITE_CUSTOMIZE_ZTXT_COMPRESSION */
1351 /* end of API added to libpng-1.5.4 */
1354 png_set_write_status_fn(png_structrp png_ptr, png_write_status_ptr write_row_fn)
1356 if (png_ptr == NULL)
1359 png_ptr->write_row_fn = write_row_fn;
1362 #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
1364 png_set_write_user_transform_fn(png_structrp png_ptr, png_user_transform_ptr
1365 write_user_transform_fn)
1367 png_debug(1, "in png_set_write_user_transform_fn");
1369 if (png_ptr == NULL)
1372 png_ptr->transformations |= PNG_USER_TRANSFORM;
1373 png_ptr->write_user_transform_fn = write_user_transform_fn;
1378 #ifdef PNG_INFO_IMAGE_SUPPORTED
1380 png_write_png(png_structrp png_ptr, png_inforp info_ptr,
1381 int transforms, voidp params)
1383 if (png_ptr == NULL || info_ptr == NULL)
1386 if ((info_ptr->valid & PNG_INFO_IDAT) == 0)
1388 png_app_error(png_ptr, "no rows for png_write_image to write");
1392 /* Write the file header information. */
1393 png_write_info(png_ptr, info_ptr);
1395 /* ------ these transformations don't touch the info structure ------- */
1397 /* Invert monochrome pixels */
1398 if ((transforms & PNG_TRANSFORM_INVERT_MONO) != 0)
1399 #ifdef PNG_WRITE_INVERT_SUPPORTED
1400 png_set_invert_mono(png_ptr);
1402 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_MONO not supported");
1405 /* Shift the pixels up to a legal bit depth and fill in
1406 * as appropriate to correctly scale the image.
1408 if ((transforms & PNG_TRANSFORM_SHIFT) != 0)
1409 #ifdef PNG_WRITE_SHIFT_SUPPORTED
1410 if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
1411 png_set_shift(png_ptr, &info_ptr->sig_bit);
1413 png_app_error(png_ptr, "PNG_TRANSFORM_SHIFT not supported");
1416 /* Pack pixels into bytes */
1417 if ((transforms & PNG_TRANSFORM_PACKING) != 0)
1418 #ifdef PNG_WRITE_PACK_SUPPORTED
1419 png_set_packing(png_ptr);
1421 png_app_error(png_ptr, "PNG_TRANSFORM_PACKING not supported");
1424 /* Swap location of alpha bytes from ARGB to RGBA */
1425 if ((transforms & PNG_TRANSFORM_SWAP_ALPHA) != 0)
1426 #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED
1427 png_set_swap_alpha(png_ptr);
1429 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ALPHA not supported");
1432 /* Remove a filler (X) from XRGB/RGBX/AG/GA into to convert it into
1433 * RGB, note that the code expects the input color type to be G or RGB; no
1436 if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
1437 PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
1439 #ifdef PNG_WRITE_FILLER_SUPPORTED
1440 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
1442 if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1443 png_app_error(png_ptr,
1444 "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
1446 /* Continue if ignored - this is the pre-1.6.10 behavior */
1447 png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
1450 else if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
1451 png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
1453 png_app_error(png_ptr, "PNG_TRANSFORM_STRIP_FILLER not supported");
1457 /* Flip BGR pixels to RGB */
1458 if ((transforms & PNG_TRANSFORM_BGR) != 0)
1459 #ifdef PNG_WRITE_BGR_SUPPORTED
1460 png_set_bgr(png_ptr);
1462 png_app_error(png_ptr, "PNG_TRANSFORM_BGR not supported");
1465 /* Swap bytes of 16-bit files to most significant byte first */
1466 if ((transforms & PNG_TRANSFORM_SWAP_ENDIAN) != 0)
1467 #ifdef PNG_WRITE_SWAP_SUPPORTED
1468 png_set_swap(png_ptr);
1470 png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
1473 /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
1474 if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
1475 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
1476 png_set_packswap(png_ptr);
1478 png_app_error(png_ptr, "PNG_TRANSFORM_PACKSWAP not supported");
1481 /* Invert the alpha channel from opacity to transparency */
1482 if ((transforms & PNG_TRANSFORM_INVERT_ALPHA) != 0)
1483 #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED
1484 png_set_invert_alpha(png_ptr);
1486 png_app_error(png_ptr, "PNG_TRANSFORM_INVERT_ALPHA not supported");
1489 /* ----------------------- end of transformations ------------------- */
1491 /* Write the bits */
1492 png_write_image(png_ptr, info_ptr->row_pointers);
1494 /* It is REQUIRED to call this to finish writing the rest of the file */
1495 png_write_end(png_ptr, info_ptr);
1501 #ifdef PNG_WRITE_APNG_SUPPORTED
1503 png_write_frame_head(png_structp png_ptr, png_infop info_ptr,
1504 png_bytepp row_pointers, png_uint_32 width, png_uint_32 height,
1505 png_uint_32 x_offset, png_uint_32 y_offset,
1506 png_uint_16 delay_num, png_uint_16 delay_den, png_byte dispose_op,
1509 png_debug(1, "in png_write_frame_head");
1511 /* there is a chance this has been set after png_write_info was called,
1512 * so it would be set but not written. is there a way to be sure? */
1513 if (!(info_ptr->valid & PNG_INFO_acTL))
1514 png_error(png_ptr, "png_write_frame_head(): acTL not set");
1516 png_write_reset(png_ptr);
1518 png_write_reinit(png_ptr, info_ptr, width, height);
1520 if ( !(png_ptr->num_frames_written == 0 &&
1521 (png_ptr->apng_flags & PNG_FIRST_FRAME_HIDDEN) ) )
1522 png_write_fcTL(png_ptr, width, height, x_offset, y_offset,
1523 delay_num, delay_den, dispose_op, blend_op);
1525 PNG_UNUSED(row_pointers)
1529 png_write_frame_tail(png_structp png_ptr, png_infop info_ptr)
1531 png_debug(1, "in png_write_frame_tail");
1533 png_ptr->num_frames_written++;
1535 PNG_UNUSED(info_ptr)
1537 #endif /* PNG_WRITE_APNG_SUPPORTED */
1539 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
1540 /* Initialize the write structure - general purpose utility. */
1542 png_image_write_init(png_imagep image)
1544 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
1545 png_safe_error, png_safe_warning);
1547 if (png_ptr != NULL)
1549 png_infop info_ptr = png_create_info_struct(png_ptr);
1551 if (info_ptr != NULL)
1553 png_controlp control = png_voidcast(png_controlp,
1554 png_malloc_warn(png_ptr, (sizeof *control)));
1556 if (control != NULL)
1558 memset(control, 0, (sizeof *control));
1560 control->png_ptr = png_ptr;
1561 control->info_ptr = info_ptr;
1562 control->for_write = 1;
1564 image->opaque = control;
1568 /* Error clean up */
1569 png_destroy_info_struct(png_ptr, &info_ptr);
1572 png_destroy_write_struct(&png_ptr, NULL);
1575 return png_image_error(image, "png_image_write_: out of memory");
1578 /* Arguments to png_image_write_main: */
1583 png_const_voidp buffer;
1584 png_int_32 row_stride;
1585 png_const_voidp colormap;
1586 int convert_to_8bit;
1587 /* Local variables: */
1588 png_const_voidp first_row;
1589 ptrdiff_t row_bytes;
1590 png_voidp local_row;
1591 /* Byte count for memory writing */
1593 png_alloc_size_t memory_bytes; /* not used for STDIO */
1594 png_alloc_size_t output_bytes; /* running total */
1595 } png_image_write_control;
1597 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
1598 * do any necessary byte swapping. The component order is defined by the
1599 * png_image format value.
1602 png_write_image_16bit(png_voidp argument)
1604 png_image_write_control *display = png_voidcast(png_image_write_control*,
1606 png_imagep image = display->image;
1607 png_structrp png_ptr = image->opaque->png_ptr;
1609 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1610 display->first_row);
1611 png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
1612 png_uint_16p row_end;
1613 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1616 png_uint_32 y = image->height;
1618 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1620 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1621 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1624 ++input_row; /* To point to the first component */
1628 aindex = (int)channels;
1630 aindex = (int)channels;
1635 png_error(png_ptr, "png_write_image: internal call error");
1637 /* Work out the output row end and count over this, note that the increment
1638 * above to 'row' means that row_end can actually be beyond the end of the
1639 * row; this is correct.
1641 row_end = output_row + image->width * (channels+1);
1645 png_const_uint_16p in_ptr = input_row;
1646 png_uint_16p out_ptr = output_row;
1648 while (out_ptr < row_end)
1650 png_uint_16 alpha = in_ptr[aindex];
1651 png_uint_32 reciprocal = 0;
1654 out_ptr[aindex] = alpha;
1656 /* Calculate a reciprocal. The correct calculation is simply
1657 * component/alpha*65535 << 15. (I.e. 15 bits of precision); this
1658 * allows correct rounding by adding .5 before the shift. 'reciprocal'
1659 * is only initialized when required.
1661 if (alpha > 0 && alpha < 65535)
1662 reciprocal = ((0xffff<<15)+(alpha>>1))/alpha;
1665 do /* always at least one channel */
1667 png_uint_16 component = *in_ptr++;
1669 /* The following gives 65535 for an alpha of 0, which is fine,
1670 * otherwise if 0/0 is represented as some other value there is more
1671 * likely to be a discontinuity which will probably damage
1672 * compression when moving from a fully transparent area to a
1673 * nearly transparent one. (The assumption here is that opaque
1674 * areas tend not to be 0 intensity.)
1676 if (component >= alpha)
1679 /* component<alpha, so component/alpha is less than one and
1680 * component*reciprocal is less than 2^31.
1682 else if (component > 0 && alpha < 65535)
1684 png_uint_32 calc = component * reciprocal;
1685 calc += 16384; /* round to nearest */
1686 component = (png_uint_16)(calc >> 15);
1689 *out_ptr++ = component;
1693 /* Skip to next component (skip the intervening alpha channel) */
1698 png_write_row(png_ptr, png_voidcast(png_const_bytep, display->local_row));
1699 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1705 /* Given 16-bit input (1 to 4 channels) write 8-bit output. If an alpha channel
1706 * is present it must be removed from the components, the components are then
1707 * written in sRGB encoding. No components are added or removed.
1709 * Calculate an alpha reciprocal to reverse pre-multiplication. As above the
1710 * calculation can be done to 15 bits of accuracy; however, the output needs to
1711 * be scaled in the range 0..255*65535, so include that scaling here.
1713 # define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+((alpha)>>1))/(alpha))
1716 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
1717 png_uint_32 reciprocal/*from the above macro*/)
1719 /* The following gives 1.0 for an alpha of 0, which is fine, otherwise if 0/0
1720 * is represented as some other value there is more likely to be a
1721 * discontinuity which will probably damage compression when moving from a
1722 * fully transparent area to a nearly transparent one. (The assumption here
1723 * is that opaque areas tend not to be 0 intensity.)
1725 * There is a rounding problem here; if alpha is less than 128 it will end up
1726 * as 0 when scaled to 8 bits. To avoid introducing spurious colors into the
1727 * output change for this too.
1729 if (component >= alpha || alpha < 128)
1732 /* component<alpha, so component/alpha is less than one and
1733 * component*reciprocal is less than 2^31.
1735 else if (component > 0)
1737 /* The test is that alpha/257 (rounded) is less than 255, the first value
1738 * that becomes 255 is 65407.
1739 * NOTE: this must agree with the PNG_DIV257 macro (which must, therefore,
1740 * be exact!) [Could also test reciprocal != 0]
1744 component *= reciprocal;
1745 component += 64; /* round to nearest */
1752 /* Convert the component to sRGB. */
1753 return (png_byte)PNG_sRGB_FROM_LINEAR(component);
1761 png_write_image_8bit(png_voidp argument)
1763 png_image_write_control *display = png_voidcast(png_image_write_control*,
1765 png_imagep image = display->image;
1766 png_structrp png_ptr = image->opaque->png_ptr;
1768 png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
1769 display->first_row);
1770 png_bytep output_row = png_voidcast(png_bytep, display->local_row);
1771 png_uint_32 y = image->height;
1772 unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ?
1775 if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
1780 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
1781 if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
1784 ++input_row; /* To point to the first component */
1790 aindex = (int)channels;
1792 /* Use row_end in place of a loop counter: */
1793 row_end = output_row + image->width * (channels+1);
1797 png_const_uint_16p in_ptr = input_row;
1798 png_bytep out_ptr = output_row;
1800 while (out_ptr < row_end)
1802 png_uint_16 alpha = in_ptr[aindex];
1803 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1804 png_uint_32 reciprocal = 0;
1807 /* Scale and write the alpha channel. */
1808 out_ptr[aindex] = alphabyte;
1810 if (alphabyte > 0 && alphabyte < 255)
1811 reciprocal = UNP_RECIPROCAL(alpha);
1814 do /* always at least one channel */
1815 *out_ptr++ = png_unpremultiply(*in_ptr++, alpha, reciprocal);
1818 /* Skip to next component (skip the intervening alpha channel) */
1821 } /* while out_ptr < row_end */
1823 png_write_row(png_ptr, png_voidcast(png_const_bytep,
1824 display->local_row));
1825 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1831 /* No alpha channel, so the row_end really is the end of the row and it
1832 * is sufficient to loop over the components one by one.
1834 png_bytep row_end = output_row + image->width * channels;
1838 png_const_uint_16p in_ptr = input_row;
1839 png_bytep out_ptr = output_row;
1841 while (out_ptr < row_end)
1843 png_uint_32 component = *in_ptr++;
1846 *out_ptr++ = (png_byte)PNG_sRGB_FROM_LINEAR(component);
1849 png_write_row(png_ptr, output_row);
1850 input_row += (png_uint_16)display->row_bytes/(sizeof (png_uint_16));
1858 png_image_set_PLTE(png_image_write_control *display)
1860 png_imagep image = display->image;
1861 const void *cmap = display->colormap;
1862 int entries = image->colormap_entries > 256 ? 256 :
1863 (int)image->colormap_entries;
1865 /* NOTE: the caller must check for cmap != NULL and entries != 0 */
1866 png_uint_32 format = image->format;
1867 unsigned int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
1869 # if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
1870 defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
1871 int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
1872 (format & PNG_FORMAT_FLAG_ALPHA) != 0;
1877 # ifdef PNG_FORMAT_BGR_SUPPORTED
1878 int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
1884 png_color palette[256];
1887 memset(tRNS, 255, (sizeof tRNS));
1888 memset(palette, 0, (sizeof palette));
1890 for (i=num_trans=0; i<entries; ++i)
1892 /* This gets automatically converted to sRGB with reversal of the
1893 * pre-multiplication if the color-map has an alpha channel.
1895 if ((format & PNG_FORMAT_FLAG_LINEAR) != 0)
1897 png_const_uint_16p entry = png_voidcast(png_const_uint_16p, cmap);
1899 entry += (unsigned int)i * channels;
1901 if ((channels & 1) != 0) /* no alpha */
1903 if (channels >= 3) /* RGB */
1905 palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1907 palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1909 palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
1914 palette[i].blue = palette[i].red = palette[i].green =
1915 (png_byte)PNG_sRGB_FROM_LINEAR(255 * *entry);
1920 png_uint_16 alpha = entry[afirst ? 0 : channels-1];
1921 png_byte alphabyte = (png_byte)PNG_DIV257(alpha);
1922 png_uint_32 reciprocal = 0;
1924 /* Calculate a reciprocal, as in the png_write_image_8bit code above
1925 * this is designed to produce a value scaled to 255*65535 when
1926 * divided by 128 (i.e. asr 7).
1928 if (alphabyte > 0 && alphabyte < 255)
1929 reciprocal = (((0xffff*0xff)<<7)+(alpha>>1))/alpha;
1931 tRNS[i] = alphabyte;
1932 if (alphabyte < 255)
1935 if (channels >= 3) /* RGB */
1937 palette[i].blue = png_unpremultiply(entry[afirst + (2 ^ bgr)],
1939 palette[i].green = png_unpremultiply(entry[afirst + 1], alpha,
1941 palette[i].red = png_unpremultiply(entry[afirst + bgr], alpha,
1946 palette[i].blue = palette[i].red = palette[i].green =
1947 png_unpremultiply(entry[afirst], alpha, reciprocal);
1951 else /* Color-map has sRGB values */
1953 png_const_bytep entry = png_voidcast(png_const_bytep, cmap);
1955 entry += (unsigned int)i * channels;
1960 tRNS[i] = entry[afirst ? 0 : 3];
1965 palette[i].blue = entry[afirst + (2 ^ bgr)];
1966 palette[i].green = entry[afirst + 1];
1967 palette[i].red = entry[afirst + bgr];
1971 tRNS[i] = entry[1 ^ afirst];
1976 palette[i].blue = palette[i].red = palette[i].green =
1993 png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
1997 png_set_tRNS(image->opaque->png_ptr, image->opaque->info_ptr, tRNS,
2000 image->colormap_entries = (png_uint_32)entries;
2004 png_image_write_main(png_voidp argument)
2006 png_image_write_control *display = png_voidcast(png_image_write_control*,
2008 png_imagep image = display->image;
2009 png_structrp png_ptr = image->opaque->png_ptr;
2010 png_inforp info_ptr = image->opaque->info_ptr;
2011 png_uint_32 format = image->format;
2013 /* The following four ints are actually booleans */
2014 int colormap = (format & PNG_FORMAT_FLAG_COLORMAP);
2015 int linear = !colormap && (format & PNG_FORMAT_FLAG_LINEAR); /* input */
2016 int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
2017 int write_16bit = linear && (display->convert_to_8bit == 0);
2019 # ifdef PNG_BENIGN_ERRORS_SUPPORTED
2020 /* Make sure we error out on any bad situation */
2021 png_set_benign_errors(png_ptr, 0/*error*/);
2024 /* Default the 'row_stride' parameter if required, also check the row stride
2025 * and total image size to ensure that they are within the system limits.
2028 unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
2030 if (image->width <= 0x7fffffffU/channels) /* no overflow */
2033 png_uint_32 png_row_stride = image->width * channels;
2035 if (display->row_stride == 0)
2036 display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
2038 if (display->row_stride < 0)
2039 check = (png_uint_32)(-display->row_stride);
2042 check = (png_uint_32)display->row_stride;
2044 if (check >= png_row_stride)
2046 /* Now check for overflow of the image buffer calculation; this
2047 * limits the whole image size to 32 bits for API compatibility with
2048 * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
2050 if (image->height > 0xffffffffU/png_row_stride)
2051 png_error(image->opaque->png_ptr, "memory image too large");
2055 png_error(image->opaque->png_ptr, "supplied row stride too small");
2059 png_error(image->opaque->png_ptr, "image row stride too large");
2062 /* Set the required transforms then write the rows in the correct order. */
2063 if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
2065 if (display->colormap != NULL && image->colormap_entries > 0)
2067 png_uint_32 entries = image->colormap_entries;
2069 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2070 entries > 16 ? 8 : (entries > 4 ? 4 : (entries > 2 ? 2 : 1)),
2071 PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
2072 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2074 png_image_set_PLTE(display);
2078 png_error(image->opaque->png_ptr,
2079 "no color-map for color-mapped image");
2083 png_set_IHDR(png_ptr, info_ptr, image->width, image->height,
2084 write_16bit ? 16 : 8,
2085 ((format & PNG_FORMAT_FLAG_COLOR) ? PNG_COLOR_MASK_COLOR : 0) +
2086 ((format & PNG_FORMAT_FLAG_ALPHA) ? PNG_COLOR_MASK_ALPHA : 0),
2087 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2089 /* Counter-intuitively the data transformations must be called *after*
2090 * png_write_info, not before as in the read code, but the 'set' functions
2091 * must still be called before. Just set the color space information, never
2092 * write an interlaced image.
2095 if (write_16bit != 0)
2097 /* The gamma here is 1.0 (linear) and the cHRM chunk matches sRGB. */
2098 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_LINEAR);
2100 if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2101 png_set_cHRM_fixed(png_ptr, info_ptr,
2103 /* white */ 31270, 32900,
2104 /* red */ 64000, 33000,
2105 /* green */ 30000, 60000,
2106 /* blue */ 15000, 6000
2110 else if ((image->flags & PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB) == 0)
2111 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_PERCEPTUAL);
2113 /* Else writing an 8-bit file and the *colors* aren't sRGB, but the 8-bit
2114 * space must still be gamma encoded.
2117 png_set_gAMA_fixed(png_ptr, info_ptr, PNG_GAMMA_sRGB_INVERSE);
2119 /* Write the file header. */
2120 png_write_info(png_ptr, info_ptr);
2122 /* Now set up the data transformations (*after* the header is written),
2123 * remove the handled transformations from the 'format' flags for checking.
2125 * First check for a little endian system if writing 16-bit files.
2127 if (write_16bit != 0)
2129 png_uint_16 le = 0x0001;
2131 if ((*(png_const_bytep) & le) != 0)
2132 png_set_swap(png_ptr);
2135 # ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
2136 if ((format & PNG_FORMAT_FLAG_BGR) != 0)
2138 if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
2139 png_set_bgr(png_ptr);
2140 format &= ~PNG_FORMAT_FLAG_BGR;
2144 # ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
2145 if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
2147 if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
2148 png_set_swap_alpha(png_ptr);
2149 format &= ~PNG_FORMAT_FLAG_AFIRST;
2153 /* If there are 16 or fewer color-map entries we wrote a lower bit depth
2154 * above, but the application data is still byte packed.
2156 if (colormap != 0 && image->colormap_entries <= 16)
2157 png_set_packing(png_ptr);
2159 /* That should have handled all (both) the transforms. */
2160 if ((format & ~(png_uint_32)(PNG_FORMAT_FLAG_COLOR | PNG_FORMAT_FLAG_LINEAR |
2161 PNG_FORMAT_FLAG_ALPHA | PNG_FORMAT_FLAG_COLORMAP)) != 0)
2162 png_error(png_ptr, "png_write_image: unsupported transformation");
2165 png_const_bytep row = png_voidcast(png_const_bytep, display->buffer);
2166 ptrdiff_t row_bytes = display->row_stride;
2169 row_bytes *= (sizeof (png_uint_16));
2172 row += (image->height-1) * (-row_bytes);
2174 display->first_row = row;
2175 display->row_bytes = row_bytes;
2178 /* Apply 'fast' options if the flag is set. */
2179 if ((image->flags & PNG_IMAGE_FLAG_FAST) != 0)
2181 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_NO_FILTERS);
2182 /* NOTE: determined by experiment using pngstest, this reflects some
2183 * balance between the time to write the image once and the time to read
2184 * it about 50 times. The speed-up in pngstest was about 10-20% of the
2185 * total (user) time on a heavily loaded system.
2187 # ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
2188 png_set_compression_level(png_ptr, 3);
2192 /* Check for the cases that currently require a pre-transform on the row
2193 * before it is written. This only applies when the input is 16-bit and
2194 * either there is an alpha channel or it is converted to 8-bit.
2196 if ((linear != 0 && alpha != 0 ) ||
2197 (colormap == 0 && display->convert_to_8bit != 0))
2199 png_bytep row = png_voidcast(png_bytep, png_malloc(png_ptr,
2200 png_get_rowbytes(png_ptr, info_ptr)));
2203 display->local_row = row;
2204 if (write_16bit != 0)
2205 result = png_safe_execute(image, png_write_image_16bit, display);
2207 result = png_safe_execute(image, png_write_image_8bit, display);
2208 display->local_row = NULL;
2210 png_free(png_ptr, row);
2212 /* Skip the 'write_end' on error: */
2217 /* Otherwise this is the case where the input is in a format currently
2218 * supported by the rest of the libpng write code; call it directly.
2222 png_const_bytep row = png_voidcast(png_const_bytep, display->first_row);
2223 ptrdiff_t row_bytes = display->row_bytes;
2224 png_uint_32 y = image->height;
2228 png_write_row(png_ptr, row);
2233 png_write_end(png_ptr, info_ptr);
2238 static void (PNGCBAPI
2239 image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data, size_t size)
2241 png_image_write_control *display = png_voidcast(png_image_write_control*,
2242 png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
2243 png_alloc_size_t ob = display->output_bytes;
2245 /* Check for overflow; this should never happen: */
2246 if (size <= ((png_alloc_size_t)-1) - ob)
2248 /* I don't think libpng ever does this, but just in case: */
2251 if (display->memory_bytes >= ob+size) /* writing */
2252 memcpy(display->memory+ob, data, size);
2254 /* Always update the size: */
2255 display->output_bytes = ob+size;
2260 png_error(png_ptr, "png_image_write_to_memory: PNG too big");
2263 static void (PNGCBAPI
2264 image_memory_flush)(png_structp png_ptr)
2270 png_image_write_memory(png_voidp argument)
2272 png_image_write_control *display = png_voidcast(png_image_write_control*,
2275 /* The rest of the memory-specific init and write_main in an error protected
2276 * environment. This case needs to use callbacks for the write operations
2277 * since libpng has no built in support for writing to memory.
2279 png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
2280 image_memory_write, image_memory_flush);
2282 return png_image_write_main(display);
2286 png_image_write_to_memory(png_imagep image, void *memory,
2287 png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
2288 const void *buffer, png_int_32 row_stride, const void *colormap)
2290 /* Write the image to the given buffer, or count the bytes if it is NULL */
2291 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2293 if (memory_bytes != NULL && buffer != NULL)
2295 /* This is to give the caller an easier error detection in the NULL
2296 * case and guard against uninitialized variable problems:
2301 if (png_image_write_init(image) != 0)
2303 png_image_write_control display;
2306 memset(&display, 0, (sizeof display));
2307 display.image = image;
2308 display.buffer = buffer;
2309 display.row_stride = row_stride;
2310 display.colormap = colormap;
2311 display.convert_to_8bit = convert_to_8bit;
2312 display.memory = png_voidcast(png_bytep, memory);
2313 display.memory_bytes = *memory_bytes;
2314 display.output_bytes = 0;
2316 result = png_safe_execute(image, png_image_write_memory, &display);
2317 png_image_free(image);
2319 /* write_memory returns true even if we ran out of buffer. */
2322 /* On out-of-buffer this function returns '0' but still updates
2325 if (memory != NULL && display.output_bytes > *memory_bytes)
2328 *memory_bytes = display.output_bytes;
2339 return png_image_error(image,
2340 "png_image_write_to_memory: invalid argument");
2343 else if (image != NULL)
2344 return png_image_error(image,
2345 "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
2351 #ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
2353 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
2354 const void *buffer, png_int_32 row_stride, const void *colormap)
2356 /* Write the image to the given (FILE*). */
2357 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2359 if (file != NULL && buffer != NULL)
2361 if (png_image_write_init(image) != 0)
2363 png_image_write_control display;
2366 /* This is slightly evil, but png_init_io doesn't do anything other
2367 * than this and we haven't changed the standard IO functions so
2368 * this saves a 'safe' function.
2370 image->opaque->png_ptr->io_ptr = file;
2372 memset(&display, 0, (sizeof display));
2373 display.image = image;
2374 display.buffer = buffer;
2375 display.row_stride = row_stride;
2376 display.colormap = colormap;
2377 display.convert_to_8bit = convert_to_8bit;
2379 result = png_safe_execute(image, png_image_write_main, &display);
2380 png_image_free(image);
2389 return png_image_error(image,
2390 "png_image_write_to_stdio: invalid argument");
2393 else if (image != NULL)
2394 return png_image_error(image,
2395 "png_image_write_to_stdio: incorrect PNG_IMAGE_VERSION");
2402 png_image_write_to_file(png_imagep image, const char *file_name,
2403 int convert_to_8bit, const void *buffer, png_int_32 row_stride,
2404 const void *colormap)
2406 /* Write the image to the named file. */
2407 if (image != NULL && image->version == PNG_IMAGE_VERSION)
2409 if (file_name != NULL && buffer != NULL)
2411 FILE *fp = fopen(file_name, "wb");
2415 if (png_image_write_to_stdio(image, fp, convert_to_8bit, buffer,
2416 row_stride, colormap) != 0)
2418 int error; /* from fflush/fclose */
2420 /* Make sure the file is flushed correctly. */
2421 if (fflush(fp) == 0 && ferror(fp) == 0)
2423 if (fclose(fp) == 0)
2426 error = errno; /* from fclose */
2431 error = errno; /* from fflush or ferror */
2435 (void)remove(file_name);
2436 /* The image has already been cleaned up; this is just used to
2437 * set the error (because the original write succeeded).
2439 return png_image_error(image, strerror(error));
2444 /* Clean up: just the opened file. */
2446 (void)remove(file_name);
2452 return png_image_error(image, strerror(errno));
2456 return png_image_error(image,
2457 "png_image_write_to_file: invalid argument");
2460 else if (image != NULL)
2461 return png_image_error(image,
2462 "png_image_write_to_file: incorrect PNG_IMAGE_VERSION");
2467 #endif /* SIMPLIFIED_WRITE_STDIO */
2468 #endif /* SIMPLIFIED_WRITE */