4 #define COPYRIGHT "\251 2013,2015 John Cunningham Bowler"
6 * This code is released under the libpng license.
7 * For conditions of distribution and use, see the disclaimer
10 * Make a test PNG image. The arguments are as follows:
12 * makepng [--sRGB|--linear|--1.8] [--tRNS] [--nofilters] \
13 * color-type bit-depth [file-name]
15 * The color-type may be numeric (and must match the numbers used by the PNG
16 * specification) or one of the format names listed below. The bit-depth is the
17 * component bit depth, or the pixel bit-depth for a color-mapped image.
19 * Without any options no color-space information is written, with the options
20 * an sRGB or the appropriate gAMA chunk is written. "1.8" refers to the
21 * display system used on older Apple computers to correct for high ambient
22 * light levels in the viewing environment; it applies a transform of
23 * approximately value^(1/1.45) to the color values and so a gAMA chunk of 65909
24 * is written (1.45/2.2).
26 * The image data is generated internally. Unless --color is given the images
27 * used are as follows:
29 * 1 channel: a square image with a diamond, the least luminous colors are on
30 * the edge of the image, the most luminous in the center.
32 * 2 channels: the color channel increases in luminosity from top to bottom, the
33 * alpha channel increases in opacity from left to right.
35 * 3 channels: linear combinations of, from the top-left corner clockwise,
36 * black, green, white, red.
38 * 4 channels: linear combinations of, from the top-left corner clockwise,
39 * transparent, red, green, blue.
41 * For color-mapped images a four channel color-map is used and if --tRNS is
42 * given the PNG file has a tRNS chunk, as follows:
44 * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
45 * 2-bit: entry 0: transparent-green
48 * entry 3: opaque-white
49 * 4-bit: the 16 combinations of the 2-bit case
50 * 8-bit: the 256 combinations of the 4-bit case
52 * The palette always has 2^bit-depth entries and the tRNS chunk one fewer. The
53 * image is the 1-channel diamond, but using palette index, not luminosity.
55 * For formats other than color-mapped ones if --tRNS is specified a tRNS chunk
56 * is generated with all channels equal to the low bits of 0x0101.
58 * Image size is determined by the final pixel depth in bits, i.e. channels x
59 * bit-depth, as follows:
61 * 8 bits or less: 64x64
63 * More than 16 bits: 1024x1024
65 * Row filtering is the libpng default but may be turned off (the 'none' filter
66 * is used on every row) with the --nofilters option.
68 * The images are not interlaced.
70 * If file-name is given then the PNG is written to that file, else it is
71 * written to stdout. Notice that stdout is not supported on systems where, by
72 * default, it assumes text output; this program makes no attempt to change the
73 * text mode of stdout!
75 * makepng --color=<color> ...
77 * If --color is given then the whole image has that color, color-mapped images
78 * will have exactly one palette entry and all image files with be 16x16 in
79 * size. The color value is 1 to 4 decimal numbers as appropriate for the color
84 * If --small is given the images are no larger than required to include every
85 * possible pixel value for the format.
87 * For formats with pixels 8 bits or fewer in size the images consist of a
88 * single row with 2^pixel-depth pixels, one of every possible value.
90 * For formats with 16-bit pixels a 256x256 image is generated containing every
91 * possible pixel value.
93 * For larger pixel sizes a 256x256 image is generated where the first row
94 * consists of each pixel that has identical byte values throughout the pixel
95 * followed by rows where the byte values differ within the pixel.
97 * In all cases the pixel values are arranged in such a way that the SUB and UP
98 * filters give byte sequences for maximal zlib compression. By default (if
99 * --nofilters is not given) the SUB filter is used on the first row and the UP
100 * filter on all following rows.
102 * The --small option is meant to provide good test-case coverage, however the
103 * images are not easy to examine visually. Without the --small option the
104 * images contain identical color values; the pixel values are adjusted
105 * according to the gamma encoding with no gamma encoding being interpreted as
111 * This code is copyright of the authors, see the COPYRIGHT define above. The
112 * code is licensed as above, using the libpng license. The code generates
113 * images which are solely the product of the code; the options choose which of
114 * the many possibilities to generate. The images that result (but not the code
115 * which generates them) are licensed as defined here:
117 * IMPORTANT: the COPYRIGHT #define must contain ISO-Latin-1 characters, the
118 * IMAGE_LICENSING #define must contain UTF-8 characters. The 'copyright'
119 * symbol 0xA9U (\251) in ISO-Latin-1 encoding and 0xC20xA9 (\302\251) in UTF-8.
121 #define IMAGE_LICENSING "Dedicated to the public domain per Creative Commons "\
122 "license \"CC0 1.0\"; https://creativecommons.org/publicdomain/zero/1.0/"
124 #include <stddef.h> /* for offsetof */
134 #if defined(HAVE_CONFIG_H) && !defined(PNG_NO_CONFIG_H)
138 /* Define the following to use this test against your installed libpng, rather
139 * than the one being built here:
141 #ifdef PNG_FREESTANDING_TESTS
144 # include "../../png.h"
149 /* Work round for GCC complaints about casting a (double) function result to
156 return (unsigned int)d;
166 /* This structure is used for inserting extra chunks (the --insert argument, not
169 typedef struct chunk_insert
171 struct chunk_insert *next;
172 void (*insert)(png_structp, png_infop, int, png_charpp);
174 png_charp parameters[1];
178 channels_of_type(int color_type)
180 if (color_type & PNG_COLOR_MASK_PALETTE)
187 if (color_type & PNG_COLOR_MASK_COLOR)
190 if (color_type & PNG_COLOR_MASK_ALPHA)
199 pixel_depth_of_type(int color_type, int bit_depth)
201 return channels_of_type(color_type) * bit_depth;
205 image_size_of_type(int color_type, int bit_depth, unsigned int *colors,
213 int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
217 if (pixel_depth <= 8) /* there will be one row */
218 return 1 << pixel_depth;
224 else if (pixel_depth < 8)
227 else if (pixel_depth > 16)
236 set_color(png_colorp color, png_bytep trans, unsigned int red,
237 unsigned int green, unsigned int blue, unsigned int alpha,
238 png_const_bytep gamma_table)
240 color->red = gamma_table[red];
241 color->green = gamma_table[green];
242 color->blue = gamma_table[blue];
243 *trans = (png_byte)alpha;
247 generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
248 png_const_bytep gamma_table, unsigned int *colors)
251 * 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
252 * 2-bit: entry 0: transparent-green
255 * entry 3: opaque-white
256 * 4-bit: the 16 combinations of the 2-bit case
257 * 8-bit: the 256 combinations of the 4-bit case
262 fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
267 set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
272 set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
273 colors[2], gamma_table);
277 set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
282 set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
283 colors[4], gamma_table);
289 set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
290 set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
296 unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
298 volatile unsigned int ip = 0;
300 for (x=0; x<size; ++x)
302 for (y=0; y<size; ++y)
306 /* size is at most 16, so the scaled value below fits in 16 bits
308 # define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
309 # define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
310 (interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
313 set_color(palette+ip, trans+ip,
314 /* color: green, red,blue,white */
315 xyinterp(x, y, 0, 255, 0, 255),
316 xyinterp(x, y, 255, 0, 0, 255),
317 xyinterp(x, y, 0, 0, 255, 255),
318 /* alpha: 0, 102, 204, 255) */
319 xyinterp(x, y, 0, 102, 204, 255),
330 set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
331 png_uint_32 value, png_const_bytep gamma_table, double conv)
333 unsigned int mask = (1U << bit_depth)-1;
335 x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
339 png_uint_32 offset = x >> 3;
341 if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
350 /* Don't gamma correct - values get smashed */
352 unsigned int shift = (8 - bit_depth) - (x & 0x7U);
355 value = (value << shift) & mask;
356 *row = (png_byte)((*row & ~mask) | value);
361 fprintf(stderr, "makepng: bad bit depth (internal error)\n");
365 value = flooru(65535*pow(value/65535.,conv)+.5);
366 *row++ = (png_byte)(value >> 8);
367 *row = (png_byte)value;
371 *row = gamma_table[value];
378 fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
385 fprintf(stderr, "makepng: component overflow (internal error)\n");
390 static int /* filter mask for row */
391 generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type,
392 int bit_depth, png_const_bytep gamma_table, double conv,
393 unsigned int *colors, int small)
395 int filters = 0; /* file *MASK*, 0 means the default, not NONE */
396 png_uint_32 size_max =
397 image_size_of_type(color_type, bit_depth, colors, small)-1;
398 png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */
400 if (colors[0] == 0 && small)
402 unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
404 /* For pixel depths less than 16 generate a single row containing all the
405 * possible pixel values. For 16 generate all 65536 byte pair
406 * combinations in a 256x256 pixel array.
411 assert(y == 0 && rowbytes == 1 && size_max == 1);
412 row[0] = 0x6CU; /* binary: 01101100, only top 2 bits used */
413 filters = PNG_FILTER_NONE;
417 assert(y == 0 && rowbytes == 1 && size_max == 3);
418 row[0] = 0x1BU; /* binary 00011011, all bits used */
419 filters = PNG_FILTER_NONE;
423 assert(y == 0 && rowbytes == 8 && size_max == 15);
425 row[1] = 0x23U; /* SUB gives 0x22U for all following bytes */
432 filters = PNG_FILTER_SUB;
436 /* The row will have all the pixel values in order starting with
437 * '1', the SUB filter will change every byte into '1' (including
438 * the last, which generates pixel value '0'). Since the SUB filter
439 * has value 1 this should result in maximum compression.
441 assert(y == 0 && rowbytes == 256 && size_max == 255);
444 row[size_max] = 0xFFU & (size_max+1);
449 filters = PNG_FILTER_SUB;
453 /* Rows are generated such that each row has a constant difference
454 * between the first and second byte of each pixel and so that the
455 * difference increases by 1 at each row. The rows start with the
456 * first byte value of 0 and the value increases to 255 across the
459 * The difference starts at 1, so the first row is:
461 * 0 1 1 2 2 3 3 4 ... 254 255 255 0
463 * This means that running the SUB filter on the first row produces:
465 * [SUB==1] 0 1 0 1 0 1...
467 * Then the difference is 2 on the next row, giving:
469 * 0 2 1 3 2 4 3 5 ... 254 0 255 1
471 * When the UP filter is run on this libpng produces:
473 * [UP ==2] 0 1 0 1 0 1...
475 * And so on for all the remain rows to the final two * rows:
477 * row 254: 0 255 1 0 2 1 3 2 4 3 ... 254 253 255 254
478 * row 255: 0 0 1 1 2 2 3 3 4 4 ... 254 254 255 255
480 assert(rowbytes == 512 && size_max == 255);
483 row[2*size_max ] = 0xFFU & size_max;
484 row[2*size_max+1] = 0xFFU & (size_max+y+1);
489 /* The first row must include PNG_FILTER_UP so that libpng knows we
490 * need to keep it for the following row:
492 filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
499 /* The rows are filled by an alogorithm similar to the above, in the
500 * first row pixel bytes are all equal, increasing from 0 by 1 for
501 * each pixel. In the second row the bytes within a pixel are
502 * incremented 1,3,5,7,... from the previous row byte. Using an odd
503 * number ensures all the possible byte values are used.
505 assert(size_max == 255 && rowbytes == 256*(pixel_depth>>3));
506 pixel_depth >>= 3; /* now in bytes */
509 const size_t pixel_index = --rowbytes/pixel_depth;
512 row[rowbytes] = 0xFFU & pixel_index;
516 const size_t byte_offset =
517 rowbytes - pixel_index * pixel_depth;
520 0xFFU & (pixel_index + (byte_offset * 2*y) + 1);
523 filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
527 assert(0/*NOT REACHED*/);
531 else switch (channels_of_type(color_type))
533 /* 1 channel: a square image with a diamond, the least luminous colors are on
534 * the edge of the image, the most luminous in the center.
539 png_uint_32 base = 2*size_max - abs(2*y-size_max);
541 for (x=0; x<=size_max; ++x)
543 png_uint_32 luma = base - abs(2*x-size_max);
545 /* 'luma' is now in the range 0..2*size_max, we need
548 luma = (luma*depth_max + size_max) / (2*size_max);
549 set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv);
554 /* 2 channels: the color channel increases in luminosity from top to bottom,
555 * the alpha channel increases in opacity from left to right.
559 png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max);
562 for (x=0; x<=size_max; ++x)
564 set_value(row, rowbytes, 2*x, bit_depth,
565 (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table,
567 set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
573 /* 3 channels: linear combinations of, from the top-left corner clockwise,
574 * black, green, white, red.
578 /* x0: the black->red scale (the value of the red component) at the
579 * start of the row (blue and green are 0).
580 * x1: the green->white scale (the value of the red and blue
581 * components at the end of the row; green is depth_max).
583 png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
586 /* Interpolate x/depth_max from start to end:
588 * start end difference
590 * green: 0 depth_max depth_max
593 for (x=0; x<=size_max; ++x)
595 set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y,
597 set_value(row, rowbytes, 3*x+1, bit_depth, /* green */
598 (depth_max * x * 2 + size_max) / (2 * size_max),
600 set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */
601 (Y * x * 2 + size_max) / (2 * size_max),
607 /* 4 channels: linear combinations of, from the top-left corner clockwise,
608 * transparent, red, green, blue.
612 /* x0: the transparent->blue scale (the value of the blue and alpha
613 * components) at the start of the row (red and green are 0).
614 * x1: the red->green scale (the value of the red and green
615 * components at the end of the row; blue is 0 and alpha is
618 png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
621 /* Interpolate x/depth_max from start to end:
623 * start end difference
624 * red: 0 depth_max-Y depth_max-Y
627 * alpha: Y depth_max depth_max-Y
629 for (x=0; x<=size_max; ++x)
631 set_value(row, rowbytes, 4*x+0, bit_depth, /* red */
632 ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
634 set_value(row, rowbytes, 4*x+1, bit_depth, /* green */
635 (Y * x * 2 + size_max) / (2 * size_max),
637 set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */
638 Y - (Y * x * 2 + size_max) / (2 * size_max),
640 set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */
641 Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
648 fprintf(stderr, "makepng: internal bad channel count\n");
652 else if (color_type & PNG_COLOR_MASK_PALETTE)
654 /* Palette with fixed color: the image rows are all 0 and the image width
657 memset(row, 0, rowbytes);
660 else if (colors[0] == channels_of_type(color_type))
661 switch (channels_of_type(color_type))
665 png_uint_32 luma = colors[1];
668 for (x=0; x<=size_max; ++x)
669 set_value(row, rowbytes, x, bit_depth, luma, gamma_table,
676 png_uint_32 luma = colors[1];
677 png_uint_32 alpha = colors[2];
680 for (x=0; x<size_max; ++x)
682 set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table,
684 set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
692 png_uint_32 red = colors[1];
693 png_uint_32 green = colors[2];
694 png_uint_32 blue = colors[3];
697 for (x=0; x<=size_max; ++x)
699 set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table,
701 set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table,
703 set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table,
711 png_uint_32 red = colors[1];
712 png_uint_32 green = colors[2];
713 png_uint_32 blue = colors[3];
714 png_uint_32 alpha = colors[4];
717 for (x=0; x<=size_max; ++x)
719 set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table,
721 set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table,
723 set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table,
725 set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table,
732 fprintf(stderr, "makepng: internal bad channel count\n");
739 "makepng: --color: count(%u) does not match channels(%u)\n",
740 colors[0], channels_of_type(color_type));
749 makepng_warning(png_structp png_ptr, png_const_charp message)
751 const char **ep = png_get_error_ptr(png_ptr);
754 if (ep != NULL && *ep != NULL)
760 fprintf(stderr, "%s: warning: %s\n", name, message);
764 makepng_error(png_structp png_ptr, png_const_charp message)
766 makepng_warning(png_ptr, message);
767 png_longjmp(png_ptr, 1);
770 static int /* 0 on success, else an error code */
771 write_png(const char **name, FILE *fp, int color_type, int bit_depth,
772 volatile png_fixed_point gamma, chunk_insert * volatile insert,
773 unsigned int filters, unsigned int *colors, int small, int tRNS)
775 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
776 name, makepng_error, makepng_warning);
777 volatile png_infop info_ptr = NULL;
778 volatile png_bytep row = NULL;
782 fprintf(stderr, "makepng: OOM allocating write structure\n");
786 if (setjmp(png_jmpbuf(png_ptr)))
788 png_structp nv_ptr = png_ptr;
789 png_infop nv_info = info_ptr;
793 png_destroy_write_struct(&nv_ptr, &nv_info);
794 if (row != NULL) free(row);
798 /* Allow benign errors so that we can write PNGs with errors */
799 png_set_benign_errors(png_ptr, 1/*allowed*/);
801 /* Max out the text compression level in an attempt to make the license
802 * small. If --small then do the same for the IDAT.
805 png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
807 png_set_text_compression_level(png_ptr, Z_BEST_COMPRESSION);
809 png_init_io(png_ptr, fp);
811 info_ptr = png_create_info_struct(png_ptr);
812 if (info_ptr == NULL)
813 png_error(png_ptr, "OOM allocating info structure");
817 image_size_of_type(color_type, bit_depth, colors, small);
819 png_fixed_point real_gamma = 45455; /* For sRGB */
820 png_byte gamma_table[256];
823 /* Normally images are square, but with 'small' we want to simply generate
824 * all the pixel values, or all that we reasonably can:
828 unsigned int pixel_depth =
829 pixel_depth_of_type(color_type, bit_depth);
831 if (pixel_depth <= 8U)
833 assert(size == (1U<<pixel_depth));
839 assert(size == 256U);
847 /* This function uses the libpng values used on read to carry extra
848 * information about the gamma:
850 if (gamma == PNG_GAMMA_MAC_18)
853 else if (gamma > 0 && gamma < 1000)
862 if (real_gamma == 45455)
864 for (i=0; i<256; ++i)
866 gamma_table[i] = (png_byte)i;
873 /* Convert 'i' from sRGB (45455) to real_gamma, this makes
874 * the images look the same regardless of the gAMA chunk.
881 for (i=1; i<255; ++i)
882 gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5);
884 gamma_table[255] = 255;
888 png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type,
889 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
891 if (color_type & PNG_COLOR_MASK_PALETTE)
894 png_color palette[256];
897 npalette = generate_palette(palette, trans, bit_depth, gamma_table,
899 png_set_PLTE(png_ptr, info_ptr, palette, npalette);
902 png_set_tRNS(png_ptr, info_ptr, trans, npalette-1,
903 NULL/*transparent color*/);
905 /* Reset gamma_table to prevent the image rows being changed */
906 for (npalette=0; npalette<256; ++npalette)
907 gamma_table[npalette] = (png_byte)npalette;
914 col.red = col.green = col.blue = col.gray =
915 0x0101U & ((1U<<bit_depth)-1U);
917 png_set_tRNS(png_ptr, info_ptr, NULL/*trans*/, 1U, &col);
920 if (gamma == PNG_DEFAULT_sRGB)
921 png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE);
923 else if (gamma > 0) /* Else don't set color space information */
925 png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma);
927 /* Just use the sRGB values here. */
928 png_set_cHRM_fixed(png_ptr, info_ptr,
930 /* white */ 31270, 32900,
931 /* red */ 64000, 33000,
932 /* green */ 30000, 60000,
933 /* blue */ 15000, 6000
937 /* Insert extra information. */
938 while (insert != NULL)
940 insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters);
941 insert = insert->next;
944 /* Write the file header. */
945 png_write_info(png_ptr, info_ptr);
947 /* Restrict the filters */
948 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
951 # ifdef PNG_WRITE_INTERLACING_SUPPORTED
952 int passes = png_set_interlace_handling(png_ptr);
953 # else /* !WRITE_INTERLACING */
955 # endif /* !WRITE_INTERLACING */
957 size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
959 row = malloc(rowbytes);
962 png_error(png_ptr, "OOM allocating row buffer");
964 for (pass = 0; pass < passes; ++pass)
968 for (y=0; y<ysize; ++y)
970 unsigned int row_filters =
971 generate_row(row, rowbytes, y, color_type, bit_depth,
972 gamma_table, conv, colors, small);
974 if (row_filters != 0 && filters == PNG_ALL_FILTERS)
975 png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, row_filters);
977 png_write_row(png_ptr, row);
983 /* Finish writing the file. */
984 png_write_end(png_ptr, info_ptr);
987 png_structp nv_ptr = png_ptr;
988 png_infop nv_info = info_ptr;
992 png_destroy_write_struct(&nv_ptr, &nv_info);
1000 load_file(png_const_charp name, png_bytepp result)
1002 FILE *fp = tmpfile();
1006 FILE *ip = fopen(name, "rb");
1016 if (ch == EOF) break;
1024 fprintf(stderr, "%s: read error\n", name);
1034 perror("temporary file");
1035 fprintf(stderr, "temporary file write error\n");
1044 /* Round up to a multiple of 4 here to allow an iCCP profile
1045 * to be padded to a 4x boundary.
1047 png_bytep data = malloc((total+3)&~3);
1051 size_t new_size = 0;
1056 if (ch == EOF) break;
1057 data[new_size++] = (png_byte)ch;
1060 if (ferror(fp) || new_size != total)
1062 perror("temporary file");
1063 fprintf(stderr, "temporary file read error\n");
1076 fprintf(stderr, "%s: out of memory loading file\n", name);
1080 fprintf(stderr, "%s: empty file\n", name);
1088 fprintf(stderr, "%s: open failed\n", name);
1095 fprintf(stderr, "makepng: %s: could not open temporary file\n", name);
1102 load_fake(png_charp param, png_bytepp profile)
1104 char *endptr = NULL;
1105 uint64_t size = strtoull(param, &endptr, 0/*base*/);
1107 /* The 'fake' format is <number>*[string] */
1108 if (endptr != NULL && *endptr == '*')
1110 size_t len = strlen(++endptr);
1111 size_t result = (size_t)size;
1113 if (len == 0) len = 1; /* capture the terminating '\0' */
1115 /* Now repeat that string to fill 'size' bytes. */
1116 if (result == size && (*profile = malloc(result)) != NULL)
1118 png_bytep out = *profile;
1121 memset(out, *endptr, result);
1127 memcpy(out, endptr, len);
1131 memcpy(out, endptr, size);
1139 fprintf(stderr, "%s: size exceeds system limits\n", param);
1148 check_param_count(int nparams, int expect)
1150 if (nparams != expect)
1152 fprintf(stderr, "bad parameter count (internal error)\n");
1158 insert_iCCP(png_structp png_ptr, png_infop info_ptr, int nparams,
1161 png_bytep profile = NULL;
1162 png_uint_32 proflen = 0;
1165 check_param_count(nparams, 2);
1167 switch (params[1][0])
1171 size_t filelen = load_file(params[1]+1, &profile);
1172 if (filelen > 0xfffffffc) /* Maximum profile length */
1174 fprintf(stderr, "%s: file too long (%lu) for an ICC profile\n",
1175 params[1]+1, (unsigned long)filelen);
1179 proflen = (png_uint_32)filelen;
1183 case '0': case '1': case '2': case '3': case '4':
1184 case '5': case '6': case '7': case '8': case '9':
1186 size_t fake_len = load_fake(params[1], &profile);
1188 if (fake_len > 0) /* else a simple parameter */
1190 if (fake_len > 0xffffffff) /* Maximum profile length */
1193 "%s: fake data too long (%lu) for an ICC profile\n",
1194 params[1], (unsigned long)fake_len);
1197 proflen = (png_uint_32)(fake_len & ~3U);
1198 /* Always fix up the profile length. */
1199 png_save_uint_32(profile, proflen);
1205 fprintf(stderr, "--insert iCCP \"%s\": unrecognized\n", params[1]);
1206 fprintf(stderr, " use '<' to read a file: \"<filename\"\n");
1215 "makepng: --insert iCCP %s: profile length made a multiple of 4\n",
1218 /* load_file allocates extra space for this padding, the ICC spec requires
1219 * padding with zero bytes.
1222 profile[proflen++] = 0;
1225 if (profile != NULL && proflen > 3)
1227 png_uint_32 prof_header = png_get_uint_32(profile);
1229 if (prof_header != proflen)
1231 fprintf(stderr, "--insert iCCP %s: profile length field wrong:\n",
1233 fprintf(stderr, " actual %lu, recorded value %lu (corrected)\n",
1234 (unsigned long)proflen, (unsigned long)prof_header);
1235 png_save_uint_32(profile, proflen);
1239 if (result && profile != NULL && proflen >=4)
1240 png_set_iCCP(png_ptr, info_ptr, params[0], PNG_COMPRESSION_TYPE_BASE,
1251 clear_text(png_text *text, png_charp keyword)
1253 text->compression = -1; /* none */
1254 text->key = keyword;
1256 text->text_length = 0; /* libpng calculates this */
1257 text->itxt_length = 0; /* libpng calculates this */
1259 text->lang_key = NULL;
1263 set_text(png_structp png_ptr, png_infop info_ptr, png_textp text,
1270 png_bytep file = NULL;
1272 text->text_length = load_file(param+1, &file);
1273 text->text = (png_charp)file;
1277 case '0': case '1': case '2': case '3': case '4':
1278 case '5': case '6': case '7': case '8': case '9':
1280 png_bytep data = NULL;
1281 size_t fake_len = load_fake(param, &data);
1283 if (fake_len > 0) /* else a simple parameter */
1285 text->text_length = fake_len;
1286 text->text = (png_charp)data;
1296 png_set_text(png_ptr, info_ptr, text, 1);
1298 if (text->text != param)
1303 insert_tEXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1308 check_param_count(nparams, 2);
1309 clear_text(&text, params[0]);
1310 set_text(png_ptr, info_ptr, &text, params[1]);
1314 insert_zTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1319 check_param_count(nparams, 2);
1320 clear_text(&text, params[0]);
1321 text.compression = 0; /* deflate */
1322 set_text(png_ptr, info_ptr, &text, params[1]);
1326 insert_iTXt(png_structp png_ptr, png_infop info_ptr, int nparams,
1331 check_param_count(nparams, 4);
1332 clear_text(&text, params[0]);
1333 text.compression = 2; /* iTXt + deflate */
1334 text.lang = params[1];/* language tag */
1335 text.lang_key = params[2]; /* translated keyword */
1336 set_text(png_ptr, info_ptr, &text, params[3]);
1340 insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams,
1344 png_uint_16 freq[256];
1346 /* libpng takes the count from the PLTE count; we don't check it here but we
1347 * do set the array to 0 for unspecified entries.
1349 memset(freq, 0, sizeof freq);
1350 for (i=0; i<nparams; ++i)
1352 char *endptr = NULL;
1353 unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
1355 if (params[i][0] && *endptr == 0 && l <= 65535)
1356 freq[i] = (png_uint_16)l;
1360 fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
1365 png_set_hIST(png_ptr, info_ptr, freq);
1369 bval(png_const_structrp png_ptr, png_charp param, unsigned int maxval)
1371 char *endptr = NULL;
1372 unsigned long int l = strtoul(param, &endptr, 0/*base*/);
1374 if (param[0] && *endptr == 0 && l <= maxval)
1378 png_error(png_ptr, "sBIT: invalid sBIT value");
1382 insert_sBIT(png_structp png_ptr, png_infop info_ptr, int nparams,
1385 int ct = png_get_color_type(png_ptr, info_ptr);
1386 int c = (ct & PNG_COLOR_MASK_COLOR ? 3 : 1) +
1387 (ct & PNG_COLOR_MASK_ALPHA ? 1 : 0);
1388 unsigned int maxval =
1389 ct & PNG_COLOR_MASK_PALETTE ? 8U : png_get_bit_depth(png_ptr, info_ptr);
1393 png_error(png_ptr, "sBIT: incorrect parameter count");
1395 if (ct & PNG_COLOR_MASK_COLOR)
1397 sBIT.red = bval(png_ptr, params[0], maxval);
1398 sBIT.green = bval(png_ptr, params[1], maxval);
1399 sBIT.blue = bval(png_ptr, params[2], maxval);
1405 sBIT.red = sBIT.green = sBIT.blue = 42;
1406 sBIT.gray = bval(png_ptr, params[0], maxval);
1409 if (ct & PNG_COLOR_MASK_ALPHA)
1410 sBIT.alpha = bval(png_ptr, params[nparams-1], maxval);
1415 png_set_sBIT(png_ptr, info_ptr, &sBIT);
1420 insert_sPLT(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
1422 fprintf(stderr, "insert sPLT: NYI\n");
1427 find_parameters(png_const_charp what, png_charp param, png_charp *list,
1430 /* Parameters are separated by '\n' or ':' characters, up to nparams are
1431 * accepted (more is an error) and the number found is returned.
1434 for (i=0; *param && i<nparams; ++i)
1439 if (*param == '\n' || *param == ':')
1441 *param++ = 0; /* Terminate last parameter */
1442 break; /* And start a new one. */
1449 fprintf(stderr, "--insert %s: too many parameters (%s)\n", what, param);
1453 list[i] = NULL; /* terminates list */
1454 return i; /* number of parameters filled in */
1458 bad_parameter_count(png_const_charp what, int nparams)
1460 fprintf(stderr, "--insert %s: bad parameter count %d\n", what, nparams);
1464 static chunk_insert *
1465 make_insert(png_const_charp what,
1466 void (*insert)(png_structp, png_infop, int, png_charpp),
1467 int nparams, png_charpp list)
1472 cip = malloc(offsetof(chunk_insert,parameters) +
1473 nparams * sizeof (png_charp));
1477 fprintf(stderr, "--insert %s: out of memory allocating %d parameters\n",
1483 cip->insert = insert;
1484 cip->nparams = nparams;
1485 for (i=0; i<nparams; ++i)
1486 cip->parameters[i] = list[i];
1491 static chunk_insert *
1492 find_insert(png_const_charp what, png_charp param)
1494 png_uint_32 chunk = 0;
1495 png_charp parameter_list[1024];
1498 /* Assemble the chunk name */
1503 if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
1504 chunk = (chunk << 8) + what[i];
1510 if (i < 4 || what[4] != 0)
1512 fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what);
1516 /* Assemble the parameter list. */
1517 nparams = find_parameters(what, param, parameter_list, 1024);
1519 # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
1523 case CHUNK(105,67,67,80): /* iCCP */
1525 return make_insert(what, insert_iCCP, nparams, parameter_list);
1528 case CHUNK(116,69,88,116): /* tEXt */
1530 return make_insert(what, insert_tEXt, nparams, parameter_list);
1533 case CHUNK(122,84,88,116): /* zTXt */
1535 return make_insert(what, insert_zTXt, nparams, parameter_list);
1538 case CHUNK(105,84,88,116): /* iTXt */
1540 return make_insert(what, insert_iTXt, nparams, parameter_list);
1543 case CHUNK(104,73,83,84): /* hIST */
1545 return make_insert(what, insert_hIST, nparams, parameter_list);
1548 case CHUNK(115,66,73,84): /* sBIT */
1550 return make_insert(what, insert_sBIT, nparams, parameter_list);
1554 case CHUNK(115,80,76,84): /* sPLT */
1555 return make_insert(what, insert_sPLT, nparams, parameter_list);
1559 fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n",
1564 bad_parameter_count(what, nparams);
1568 /* This is necessary because libpng expects writeable strings for things like
1569 * text chunks (maybe this should be fixed...)
1572 strstash(png_const_charp foo)
1574 /* The program indicates a memory allocation error by crashing, this is by
1579 png_charp bar = malloc(strlen(foo)+1);
1580 return strcpy(bar, foo);
1587 strstash_list(const png_const_charp *text)
1590 png_charp result, bar;
1591 const png_const_charp *line = text;
1593 while (*line != NULL)
1594 foo += strlen(*line++);
1596 result = bar = malloc(foo+1);
1599 while (*line != NULL)
1601 foo = strlen(*line);
1602 memcpy(bar, *line++, foo);
1610 /* These are used to insert Copyright and Licence fields, they allow the text to
1611 * have \n unlike the --insert option.
1613 static chunk_insert *
1614 add_tEXt(const char *key, const png_const_charp *text)
1616 static char what[5] = { 116, 69, 88, 116, 0 };
1617 png_charp parameter_list[3];
1619 parameter_list[0] = strstash(key);
1620 parameter_list[1] = strstash_list(text);
1621 parameter_list[2] = NULL;
1623 return make_insert(what, insert_tEXt, 2, parameter_list);
1626 static chunk_insert *
1627 add_iTXt(const char *key, const char *language, const char *language_key,
1628 const png_const_charp *text)
1630 static char what[5] = { 105, 84, 88, 116, 0 };
1631 png_charp parameter_list[5];
1633 parameter_list[0] = strstash(key);
1634 parameter_list[1] = strstash(language);
1635 parameter_list[2] = strstash(language_key);
1636 parameter_list[3] = strstash_list(text);
1637 parameter_list[4] = NULL;
1639 return make_insert(what, insert_iTXt, 4, parameter_list);
1642 /* This is a not-very-good parser for a sequence of numbers (including 0). It
1643 * doesn't accept some apparently valid things, but it accepts all the sensible
1647 parse_color(char *arg, unsigned int *colors)
1649 unsigned int ncolors = 0;
1651 while (*arg && ncolors < 4)
1655 unsigned long ul = strtoul(arg, &ep, 0);
1659 fprintf(stderr, "makepng --color=...'%s': too big\n", arg);
1665 fprintf(stderr, "makepng --color=...'%s': not a valid color\n", arg);
1669 if (*ep) ++ep; /* skip a separator */
1672 colors[++ncolors] = (unsigned int)ul; /* checked above */
1677 fprintf(stderr, "makepng --color=...'%s': too many values\n", arg);
1685 main(int argc, char **argv)
1688 const char *file_name = NULL;
1689 int color_type = 8; /* invalid */
1690 int bit_depth = 32; /* invalid */
1691 int small = 0; /* make full size images */
1692 int tRNS = 0; /* don't output a tRNS chunk */
1693 unsigned int colors[5];
1694 unsigned int filters = PNG_ALL_FILTERS;
1695 png_fixed_point gamma = 0; /* not set */
1696 chunk_insert *head_insert = NULL;
1697 chunk_insert **insert_ptr = &head_insert;
1699 memset(colors, 0, sizeof colors);
1703 char *arg = *++argv;
1705 if (strcmp(arg, "--small") == 0)
1711 if (strcmp(arg, "--tRNS") == 0)
1717 if (strcmp(arg, "--sRGB") == 0)
1719 gamma = PNG_DEFAULT_sRGB;
1723 if (strcmp(arg, "--linear") == 0)
1729 if (strcmp(arg, "--1.8") == 0)
1731 gamma = PNG_GAMMA_MAC_18;
1735 if (strcmp(arg, "--nofilters") == 0)
1737 filters = PNG_FILTER_NONE;
1741 if (strncmp(arg, "--color=", 8) == 0)
1743 parse_color(arg+8, colors);
1747 if (argc >= 3 && strcmp(arg, "--insert") == 0)
1749 png_const_charp what = *++argv;
1750 png_charp param = *++argv;
1751 chunk_insert *new_insert;
1755 new_insert = find_insert(what, param);
1757 if (new_insert != NULL)
1759 *insert_ptr = new_insert;
1760 insert_ptr = &new_insert->next;
1768 fprintf(stderr, "makepng: %s: invalid option\n", arg);
1772 if (strcmp(arg, "palette") == 0)
1774 color_type = PNG_COLOR_TYPE_PALETTE;
1778 if (strncmp(arg, "gray", 4) == 0)
1782 color_type = PNG_COLOR_TYPE_GRAY;
1786 else if (strcmp(arg+4, "a") == 0 ||
1787 strcmp(arg+4, "alpha") == 0 ||
1788 strcmp(arg+4, "-alpha") == 0)
1790 color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
1795 if (strncmp(arg, "rgb", 3) == 0)
1799 color_type = PNG_COLOR_TYPE_RGB;
1803 else if (strcmp(arg+3, "a") == 0 ||
1804 strcmp(arg+3, "alpha") == 0 ||
1805 strcmp(arg+3, "-alpha") == 0)
1807 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1812 if (color_type == 8 && isdigit(arg[0]))
1814 color_type = atoi(arg);
1815 if (color_type < 0 || color_type > 6 || color_type == 1 ||
1818 fprintf(stderr, "makepng: %s: not a valid color type\n", arg);
1825 if (bit_depth == 32 && isdigit(arg[0]))
1827 bit_depth = atoi(arg);
1828 if (bit_depth <= 0 || bit_depth > 16 ||
1829 (bit_depth & -bit_depth) != bit_depth)
1831 fprintf(stderr, "makepng: %s: not a valid bit depth\n", arg);
1838 if (argc == 1) /* It's the file name */
1840 fp = fopen(arg, "wb");
1843 fprintf(stderr, "%s: %s: could not open\n", arg, strerror(errno));
1851 fprintf(stderr, "makepng: %s: unknown argument\n", arg);
1853 } /* argument while loop */
1855 if (color_type == 8 || bit_depth == 32)
1857 fprintf(stderr, "usage: makepng [--small] [--sRGB|--linear|--1.8] "
1858 "[--color=...] color-type bit-depth [file-name]\n"
1859 " Make a test PNG file, by default writes to stdout.\n"
1860 " Other options are available, UTSL.\n");
1864 /* Check the colors */
1866 unsigned int lim = (color_type == PNG_COLOR_TYPE_PALETTE ? 255U :
1870 for (i=1; i<=colors[0]; ++i)
1871 if (colors[i] > lim)
1873 fprintf(stderr, "makepng: --color=...: %u out of range [0..%u]\n",
1879 /* small and colors are incompatible (will probably crash if both are used at
1882 if (small && colors[0] != 0)
1884 fprintf(stderr, "makepng: --color --small: only one at a time!\n");
1888 /* Restrict the filters for more speed to those we know are used for the
1891 if (filters == PNG_ALL_FILTERS && !small/*small provides defaults*/)
1893 if ((color_type & PNG_COLOR_MASK_PALETTE) != 0 || bit_depth < 8)
1894 filters = PNG_FILTER_NONE;
1896 else if (color_type & PNG_COLOR_MASK_COLOR) /* rgb */
1899 filters &= ~(PNG_FILTER_NONE | PNG_FILTER_AVG);
1902 filters = PNG_FILTER_SUB | PNG_FILTER_PAETH;
1905 else /* gray 8 or 16-bit */
1906 filters &= ~PNG_FILTER_NONE;
1909 /* Insert standard copyright and licence text. */
1911 static png_const_charp copyright[] =
1913 COPYRIGHT, /* ISO-Latin-1 */
1916 static png_const_charp licensing[] =
1918 IMAGE_LICENSING, /* UTF-8 */
1922 chunk_insert *new_insert;
1924 new_insert = add_tEXt("Copyright", copyright);
1925 if (new_insert != NULL)
1927 *insert_ptr = new_insert;
1928 insert_ptr = &new_insert->next;
1931 new_insert = add_iTXt("Licensing", "en", NULL, licensing);
1932 if (new_insert != NULL)
1934 *insert_ptr = new_insert;
1935 insert_ptr = &new_insert->next;
1940 int ret = write_png(&file_name, fp, color_type, bit_depth, gamma,
1941 head_insert, filters, colors, small, tRNS);
1943 if (ret != 0 && file_name != NULL)