Debian Codegraph @

converter/other/pamtowinicon.c

raw
1 #define _POSIX_SOURCE /* Make sure fdopen() is in <stdio.h> */
2 #include <assert.h>
3 #include <string.h>
4 #include <stdio.h>
5
6 #include "netpbm/pm_config.h"
7 #include "netpbm/pm_c_util.h"
8 #include "netpbm/mallocvar.h"
9 #include "netpbm/nstring.h"
10 #include "netpbm/shhopt.h"
11 #include "netpbm/pm_system.h"
12 #include "netpbm/pam.h"
13 #include "winicon.h"
14
15
16
17 struct CmdlineInfo {
18 const char * inputFileName;
19 unsigned int verbose;
20 int pngthreshold;
21 unsigned int truetransparent;
22 };
23
24
25
26 static void
27 parseCommandLine(int argc, const char **argv,
28 struct CmdlineInfo * const cmdlineP) {
29
30 optEntry * option_def;
31 unsigned int option_def_index;
32 optStruct3 opt3;
33 unsigned int pngthresholdSpec;
34
35 MALLOCARRAY_NOFAIL(option_def, 100);
36
37 option_def_index = 0;
38
39 OPTENT3(0, "verbose", OPT_FLAG, NULL,
40 &cmdlineP->verbose, 0);
41 OPTENT3(0, "pngthreshold", OPT_UINT, &cmdlineP->pngthreshold,
42 &pngthresholdSpec, 0);
43 OPTENT3(0, "truetransparent", OPT_FLAG, NULL,
44 &cmdlineP->truetransparent, 0);
45
46 opt3.opt_table = option_def;
47 opt3.short_allowed = false;
48 opt3.allowNegNum = false;
49
50 pm_optParseOptions4(&argc, argv, opt3, sizeof(opt3), 0);
51
52 if (pngthresholdSpec) {
53 if (UINT_MAX / cmdlineP->pngthreshold < cmdlineP->pngthreshold)
54 pm_error("-pngthreshold is too large: %u", cmdlineP->pngthreshold);
55 } else
56 cmdlineP->pngthreshold = 128;
57
58 if (argc-1 > 0) {
59 cmdlineP->inputFileName = argv[1];
60
61 if (argc-1 > 1)
62 pm_error("Too many arguments: %u. The only non-option "
63 "argument is the optional input file name", argc-1);
64 } else
65 cmdlineP->inputFileName = "-";
66
67 free(option_def);
68 }
69
70
71
72 static bool verbose;
73
74
75
76 struct Palette {
77 sample color[256][3];
78 unsigned int colorCt;
79 /* Number of colors in color[][] */
80 bool tooManyColors;
81 /* There are too many colors for a BMP palette (more than 256); only
82 the first 256 are in color[][]
83 */
84 };
85
86
87
88 static struct IconDir *
89 newIconDir() {
90
91 struct IconDir * dirP;
92
93 MALLOCVAR_NOFAIL(dirP);
94
95 dirP->zero = 0;
96 dirP->type = ICONDIR_TYPE_ICO;
97 dirP->count = 0;
98
99 dirP->entriesAllocCt = 0;
100 dirP->entries = NULL;
101
102 return dirP;
103 }
104
105
106
107 static void
108 freeIconDir(struct IconDir * const dirP) {
109 if (dirP->entries)
110 free(dirP->entries);
111
112 free(dirP);
113 }
114
115
116
117 static void
118 addToDirectory(struct IconDirEntry * const dirEntryP,
119 struct IconDir * const dirP) {
120 /*----------------------------------------------------------------------------
121 Add an icon to the icon directory.
122 -----------------------------------------------------------------------------*/
123 if (dirP->count + 1 > dirP->entriesAllocCt) {
124 /* Out of space in dirP->entries[]. Expand. */
125
126 dirP->entriesAllocCt += 8;
127
128 REALLOCARRAY(dirP->entries, dirP->entriesAllocCt);
129
130 if (!dirP->entries)
131 pm_error("Unable to get memory for %u entries "
132 "in the Icon directory.", dirP->entriesAllocCt);
133 }
134
135 dirP->entries[dirP->count++] = *dirEntryP;
136 }
137
138
139
140 typedef void (GetPixelFn) (tuple ** const tuples,
141 unsigned int const col,
142 unsigned int const row,
143 sample * const pixel);
144
145
146
147 static GetPixelFn get_grayscalePixel;
148
149 static void
150 get_grayscalePixel(tuple ** const tuples,
151 unsigned int const col,
152 unsigned int const row,
153 sample * const pixel) {
154 /*----------------------------------------------------------------------------
155 Get a pixel from a grayscale PAM
156 -----------------------------------------------------------------------------*/
157 pixel[0] = tuples[row][col][0];
158 pixel[1] = tuples[row][col][0];
159 pixel[2] = tuples[row][col][0];
160 }
161
162
163
164 static GetPixelFn get_rgbPixel;
165
166 static void
167 get_rgbPixel(tuple ** const tuples,
168 unsigned int const col,
169 unsigned int const row,
170 sample * const pixel) {
171 /*----------------------------------------------------------------------------
172 Get a pixel from an RGB PAM
173 -----------------------------------------------------------------------------*/
174 pixel [0] = tuples [row][col][0];
175 pixel [1] = tuples [row][col][1];
176 pixel [2] = tuples [row][col][2];
177 }
178
179
180
181 static bool
182 andMakesOpaque(const struct pam * const pamP,
183 tuple ** const tuples,
184 unsigned int const row,
185 unsigned int const col,
186 bool const haveAlpha,
187 unsigned int const alphaPlane,
188 bool const haveAnd,
189 unsigned int const andPlane) {
190 /*----------------------------------------------------------------------------
191 The AND mask makes a pixel opaque
192 -----------------------------------------------------------------------------*/
193 if (haveAnd)
194 return (pamP->maxval <= tuples[row][col][andPlane]);
195 else if (haveAlpha)
196 return (pamP->maxval <= tuples[row][col][alphaPlane]);
197 else
198 /* neither alpha channel nor AND mask: full opacity */
199 return true;
200 }
201
202
203
204 static void
205 getPalette(struct pam * const pamP,
206 tuple ** const tuples,
207 GetPixelFn * const getPixel,
208 struct Palette * const paletteP) {
209 /*----------------------------------------------------------------------------
210 Create the palette for all the colors in 'tuples'.
211 -----------------------------------------------------------------------------*/
212 unsigned int row;
213
214 paletteP->colorCt = 0; /* initial value */
215 paletteP->tooManyColors = false; /* initial value */
216
217 for (row = 0; pamP->height > row && !paletteP->tooManyColors; ++row) {
218 unsigned int col;
219 for (col = 0; pamP->width > col && !paletteP->tooManyColors; ++col) {
220 sample pixel[3];
221 unsigned int i;
222
223 getPixel(tuples, col, row, pixel);
224
225 for (i = 0; i < paletteP->colorCt; ++i) {
226 if ((paletteP->color[i][0] == pixel[0])
227 && (paletteP->color[i][1] == pixel[1])
228 && (paletteP->color[i][2] == pixel[2]))
229 break;
230 }
231 if (i == paletteP->colorCt) {
232 /* We didn't find the color. */
233 if (paletteP->colorCt >= 256) {
234 /* Image exceeds the palette capacity */
235 paletteP->tooManyColors = true;
236 } else {
237 /* Add the color to the palette */
238 paletteP->color[paletteP->colorCt][0] = pixel[0];
239 paletteP->color[paletteP->colorCt][1] = pixel[1];
240 paletteP->color[paletteP->colorCt][2] = pixel[2];
241
242 ++paletteP->colorCt;
243 }
244 }
245 }
246 }
247 }
248
249
250
251 static bool
252 realAlphaNeeded(const struct pam * const pamP,
253 tuple ** const tuples,
254 unsigned int const alphaPlane) {
255 /*----------------------------------------------------------------------------
256 A real alpha channel (in contrast to an AND mask) is needed to represent the
257 image in 'tuples', given that 'alphaPlane' is the alpha plane.
258
259 A real alpha channel is needed if any pixel is translucent (neither opaque
260 nor transparent).
261 -----------------------------------------------------------------------------*/
262 unsigned int row;
263
264 for (row = 0; row < pamP->height; ++row) {
265 unsigned int col;
266 for (col = 0; col < pamP->width; ++col) {
267 sample const opacity = tuples[row][col][alphaPlane];
268
269 if (opacity != 0 && opacity != pamP->maxval)
270 return true;
271 }
272 }
273 return false;
274 }
275
276
277
278 static void
279 writeBmpImageHeader(unsigned int const width,
280 unsigned int const height,
281 unsigned int const bpp,
282 unsigned int const rasterSize,
283 FILE * const ofP) {
284 /*----------------------------------------------------------------------------
285
286 Write BMP image header
287
288 Note: bm_height is sum of rows in XOR mask and AND mask, while
289 image_size is the size of the AND mask only.
290
291 image_size does not include the sizes of the (optional) palette
292 and the (mandatory) AND mask.
293 -----------------------------------------------------------------------------*/
294 pm_writelittlelongu (ofP, 40); /* header_size */
295 pm_writelittlelongu (ofP, width); /* bm_width */
296 pm_writelittlelongu (ofP, height *2); /* bm_height */
297 pm_writelittleshortu (ofP, 1); /* color_planes */
298 pm_writelittleshortu (ofP, bpp); /* bits_per_pixel */
299 pm_writelittlelongu (ofP, BI_RGB); /* compression_method */
300 pm_writelittlelongu (ofP, rasterSize); /* image_size */
301 pm_writelittlelongu (ofP, 0); /* horizontal_resolution*/
302 pm_writelittlelongu (ofP, 0); /* vertical_resolution */
303 pm_writelittlelongu (ofP, 0); /* colors_in_palette */
304 pm_writelittlelongu (ofP, 0); /* important_colors */
305 }
306
307
308
309 static void
310 write32BitBmp(const struct pam * const pamP,
311 tuple ** const tuples,
312 GetPixelFn * const getPixel,
313 bool const haveAlpha,
314 unsigned int const alphaPlane,
315 FILE * const ofP,
316 uint32_t * const sizeP) {
317 /*----------------------------------------------------------------------------
318 Write a 32-bit BMP encoded image to file *ofP.
319 -----------------------------------------------------------------------------*/
320 int row;
321
322 writeBmpImageHeader(pamP->width, pamP->height, 32,
323 pamP->width * 4 * pamP->height, ofP);
324
325 /* write "XOR mask" */
326 for (row = pamP->height - 1; row >= 0; --row) {
327 unsigned int col;
328 for (col = 0; col < pamP->width; ++col) {
329 sample pixel[3];
330 uint32_t val;
331
332 getPixel(tuples, col, row, pixel);
333
334 val = ((uint32_t) pixel[PAM_RED_PLANE] << 16)
335 + ((uint32_t) pixel[PAM_GRN_PLANE] << 8)
336 + ((uint32_t) pixel[PAM_BLU_PLANE] << 0)
337 ;
338
339 if (haveAlpha)
340 val += (uint32_t) tuples[row][col][alphaPlane] << 24;
341
342 pm_writelittlelongu(ofP, val);
343 }
344 }
345 *sizeP = 40 + pamP->height * pamP->width * 4;
346 }
347
348
349
350 static void
351 writeBmpPalette(const struct Palette * const paletteP,
352 unsigned int const maxColors,
353 FILE * const ofP) {
354 /*----------------------------------------------------------------------------
355 Write the palette of a BMP image.
356 -----------------------------------------------------------------------------*/
357 unsigned int i;
358
359 for (i = 0; i < paletteP->colorCt; ++i)
360 pm_writelittlelongu(ofP, 0
361 +(paletteP->color[i][PAM_RED_PLANE] << 16)
362 +(paletteP->color[i][PAM_GRN_PLANE] << 8)
363 +(paletteP->color[i][PAM_BLU_PLANE] << 0));
364
365 for (; i < maxColors; ++i)
366 pm_writelittlelongu(ofP, 0);
367 }
368
369
370
371 static void
372 writeXorMask(const struct pam * const pamP,
373 tuple ** const tuples,
374 GetPixelFn * const getPixel,
375 const struct Palette * const paletteP,
376 unsigned int const bpp,
377 FILE * const ofP) {
378 /*----------------------------------------------------------------------------
379 Write the "XOR mask" part of a BMP image.
380
381 This is what one normally thinks of as the foreground image raster.
382 -----------------------------------------------------------------------------*/
383 unsigned int const maxCol = ((pamP->width * bpp + 31) & ~31) / bpp;
384
385 int row;
386
387 for (row = pamP->height - 1; row >= 0; --row) {
388 uint8_t val;
389 uint16_t mask;
390 unsigned int col;
391
392 mask = 0x1;
393 val = 0x0;
394
395 for (col = 0; col < pamP->width; ++col) {
396 sample pixel[3];
397 unsigned int i;
398
399 mask <<= bpp;
400 val <<= bpp;
401
402 getPixel(tuples, col, row, pixel);
403
404 for (i = 0; i < paletteP->colorCt; ++i)
405 if (true
406 && (pixel[0] == paletteP->color[i][0])
407 && (pixel[1] == paletteP->color[i][1])
408 && (pixel[2] == paletteP->color[i][2]))
409 break;
410
411 assert(i < paletteP->colorCt);
412
413 val |= i;
414
415 if (mask > 0xFF) {
416 pm_writecharu(ofP, val);
417 mask = 0x1;
418 val = 0x0;
419 }
420 }
421 for (; col < maxCol; ++col) {
422 mask <<= bpp;
423 val <<= bpp;
424
425 if (mask > 0xFF) {
426 pm_writecharu(ofP, val);
427 mask = 0x1;
428 }
429 }
430 }
431 }
432
433
434
435 static void
436 writePaletteBmp(unsigned int const bpp,
437 const struct pam * const pamP,
438 tuple ** const tuples,
439 GetPixelFn * const getPixel,
440 const struct Palette * const paletteP,
441 FILE * const ofP,
442 uint32_t * const sizeP) {
443 /*----------------------------------------------------------------------------
444 Write a `BMP with palette' encoded image to file *ofP.
445
446 Unless it would be smaller as a 32-bit direct image, in which case
447 write that instead.
448 -----------------------------------------------------------------------------*/
449 unsigned int const maxColors = 1 << bpp;
450
451 unsigned int const rasterSize =
452 pamP->height *((pamP->width * bpp + 31) & ~31) / 8;
453
454 if (pamP->height * pamP->width * 4 <= maxColors * 4 + rasterSize)
455 write32BitBmp(pamP, tuples, getPixel, false /*haveAlpha*/, 0,
456 ofP, sizeP);
457 else {
458 unsigned int const headerSize = 40;
459 unsigned int const paletteSize = maxColors * 4;
460
461 writeBmpImageHeader(pamP->width, pamP->height, bpp, rasterSize, ofP);
462
463 writeBmpPalette(paletteP, maxColors, ofP);
464
465 writeXorMask(pamP, tuples, getPixel, paletteP, bpp, ofP);
466
467 *sizeP = headerSize + paletteSize + rasterSize;
468 }
469 }
470
471
472
473 static void
474 writeAndMask(const struct pam * const pamP,
475 tuple ** const tuples,
476 bool const haveAlpha,
477 unsigned int const alphaPlane,
478 bool const haveAnd,
479 unsigned int const andPlane,
480 FILE * const ofP,
481 uint32_t * const sizeP) {
482 /*----------------------------------------------------------------------------
483 Write the AND mask to file *ofP.
484 -----------------------------------------------------------------------------*/
485 unsigned int const maxCol =((pamP->width * 1 + 31) & ~31) / 1;
486
487 int row;
488 unsigned int sizeSoFar;
489
490 sizeSoFar = 0;
491
492 for (row = pamP->height - 1; row >= 0; --row) {
493 uint8_t val;
494 uint16_t mask;
495 unsigned int col;
496
497 mask = 0x1;
498 val = 0x0;
499
500 for (col = 0; col < pamP->width; ++col) {
501 mask <<= 1;
502 val <<= 1;
503
504 if (!andMakesOpaque(pamP, tuples, row, col,
505 haveAlpha, alphaPlane, haveAnd, andPlane))
506 val |= 0x1;
507
508 if (mask > 0xFF) {
509 pm_writecharu(ofP, val);
510 sizeSoFar += 1;
511 mask = 0x1;
512 val = 0x0;
513 }
514 }
515 for (; col < maxCol; ++col) {
516 mask <<= 1;
517 val <<= 1;
518
519 if (mask > 0xFF){
520 pm_writecharu(ofP, val);
521 sizeSoFar += 1;
522 mask = 0x1;
523 }
524 }
525 }
526 *sizeP = sizeSoFar;
527 }
528
529
530
531 static void
532 makeAlphaFile(const struct pam * const imagePamP,
533 tuple ** const imageTuples,
534 unsigned int const alphaPlane,
535 const char ** const alphaFileNameP) {
536
537 FILE * alphaFileP;
538 struct pam alphaPam;
539 tuple ** alphaTuples;
540 unsigned int row;
541
542 pm_make_tmpfile(&alphaFileP, alphaFileNameP);
543
544 alphaPam.size = sizeof(alphaPam);
545 alphaPam.len = PAM_STRUCT_SIZE(tuple_type);
546 alphaPam.file = alphaFileP;
547 alphaPam.format = PAM_FORMAT;
548 alphaPam.width = imagePamP->width;
549 alphaPam.height = imagePamP->height;
550 alphaPam.depth = 1;
551 alphaPam.maxval = imagePamP->maxval;
552 strcpy(alphaPam.tuple_type, PAM_PGM_TUPLETYPE);
553
554 alphaTuples = pnm_allocpamarray(&alphaPam);
555
556 assert(alphaPlane < imagePamP->depth);
557
558 for (row = 0; row < alphaPam.height; ++row) {
559 unsigned int col;
560 for (col = 0; col < alphaPam.width; ++col)
561 alphaTuples[row][col][0] = imageTuples[row][col][alphaPlane];
562 }
563
564 pnm_writepam(&alphaPam, alphaTuples);
565
566 pnm_freepamarray(alphaTuples, &alphaPam);
567
568 pm_close(alphaFileP);
569 }
570
571
572
573 struct AcceptToFileParm {
574 FILE * ofP;
575 size_t * writeCtP;
576 };
577
578 static void
579 acceptToFile(int const pipeToSuckFd,
580 void * const accepterParm) {
581
582 struct AcceptToFileParm * const parmP = accepterParm;
583
584 FILE * const inFileP = fdopen(pipeToSuckFd, "r");
585
586 bool eof;
587 size_t copyCt;
588
589 for (eof = false, copyCt = 0; !eof; ) {
590 size_t readCt;
591 unsigned char buffer[1024];
592
593 readCt = fread(buffer, 1, sizeof(buffer), inFileP);
594
595 if (readCt == 0)
596 eof = true;
597 else {
598 size_t writeCt;
599
600 writeCt = fwrite(buffer, 1, readCt, parmP->ofP);
601
602 if (writeCt != readCt)
603 pm_error("Write to images file failed. errno=%d (%s)",
604 errno, strerror(errno));
605
606 copyCt += writeCt;
607 }
608 }
609 *parmP->writeCtP = copyCt;
610 }
611
612
613
614 static void
615 writePng(const struct pam * const pamP,
616 tuple ** const tuples,
617 bool const haveAlpha,
618 unsigned int const alphaPlane,
619 bool const haveAnd,
620 unsigned int const andPlane,
621 uint32_t * const sizeP,
622 FILE * const ofP) {
623
624 struct pamtuples pamTuples;
625 size_t pngSize;
626 struct AcceptToFileParm acceptParm;
627 struct pam pam;
628
629 pam = *pamP;
630 pam.depth = pamP->depth - (haveAlpha ? 1 : 0) - (haveAnd ? 1 : 0);
631
632 pamTuples.pamP = &pam;
633 pamTuples.tuplesP = (tuple ***)&tuples;
634
635 /* We're going to fork a process to add stuff to *ofP, so we flush
636 out this process' previous writes to that file first:
637 */
638 fflush(ofP);
639
640 acceptParm.ofP = ofP;
641 acceptParm.writeCtP = &pngSize;
642
643 if (haveAlpha || haveAnd) {
644 const char * alphaFileName;
645 const char * alphaOpt;
646
647 if (haveAlpha)
648 makeAlphaFile(pamP, tuples, alphaPlane, &alphaFileName);
649 else
650 makeAlphaFile(pamP, tuples, andPlane, &alphaFileName);
651
652 strcpy (pam.tuple_type,
653 pam.depth == 3 ? PAM_PPM_TUPLETYPE: PAM_PGM_TUPLETYPE);
654
655 pm_asprintf(&alphaOpt, "-alpha=%s", alphaFileName);
656
657 pm_system_lp("pnmtopng", pm_feed_from_pamtuples, &pamTuples,
658 acceptToFile, &acceptParm,
659 "pnmtopng", alphaOpt, NULL);
660
661 pm_strfree(alphaOpt);
662
663 unlink(alphaFileName);
664 } else {
665 pm_system_lp("pnmtopng", pm_feed_from_pamtuples, &pamTuples,
666 acceptToFile, &acceptParm,
667 "pnmtopng", NULL);
668 }
669
670 *sizeP = pngSize;
671 }
672
673
674
675 static void
676 blackenXor(const struct pam * const pamP,
677 tuple ** const tuples,
678 bool const haveAlpha,
679 unsigned int const alphaPlane,
680 bool const haveAnd,
681 unsigned int const andPlane) {
682 /*----------------------------------------------------------------------------
683 Set all pixels marked as transparent in AND mask to black.
684 -----------------------------------------------------------------------------*/
685 unsigned int row;
686
687 for (row = 0; row < pamP->height; ++row) {
688 unsigned int col;
689 for (col = 0; col < pamP->width; ++col) {
690 if (!andMakesOpaque(pamP, tuples, row, col,
691 haveAlpha, alphaPlane, haveAnd, andPlane)) {
692 tuples[row][col][0] = PAM_BLACK;
693
694 if (pamP->depth >= 3) {
695 tuples[row][col][1] = PAM_BLACK;
696 tuples[row][col][2] = PAM_BLACK;
697 }
698 }
699 }
700 }
701 }
702
703
704
705 static void
706 readAndScalePam(struct pam * const pamP,
707 bool const doingPng,
708 tuple ** const tuples) {
709
710 if (doingPng) {
711 /* Read the image with its native maxval */
712 unsigned int row;
713 for (row = 0; row < pamP->height; ++row)
714 pnm_readpamrow(pamP, tuples[row]);
715 } else {
716 /* Read the image and scale to maxval 255 */
717 tuple * tuplerow;
718 unsigned int row;
719 tuplerow = pnm_allocpamrow(pamP);
720
721 for (row = 0; row < pamP->height; ++row) {
722 pnm_readpamrow(pamP, tuplerow);
723 pnm_scaletuplerow(pamP, tuples[row], tuplerow, 255);
724 }
725 pnm_freepamrow(tuplerow);
726 pamP->maxval = 255;
727 }
728 }
729
730
731
732 static void
733 determineImageType(const struct pam * const pamP,
734 tuple ** const tuples,
735 GetPixelFn ** const getPixelP,
736 bool * const haveAlphaP,
737 unsigned int * const alphaPlaneP,
738 bool * const haveAndP,
739 unsigned int * const andPlaneP) {
740
741 /* PAM input channels:
742 *
743 * 1-channel PAM: Grayscale
744 * 2-channel PAM: Grayscale +Alpha
745 * 3-channel PAM: RGB
746 * 4-channel PAM: RGB +Alpha
747 * 5-channel PAM: RGB +Alpha +AND mask
748 */
749 switch (pamP->depth) {
750 case 1:
751 *getPixelP = get_grayscalePixel;
752 *haveAlphaP = false;
753 *haveAndP = false;
754 break;
755
756 case 2:
757 *getPixelP = get_grayscalePixel;
758 if (realAlphaNeeded(pamP, tuples, 1)) {
759 *haveAlphaP = true;
760 *alphaPlaneP = 1;
761 *haveAndP = false;
762 } else {
763 *haveAlphaP = false;
764 *haveAndP = true;
765 *andPlaneP = 1;
766 }
767 break;
768
769 case 3:
770 *getPixelP = get_rgbPixel;
771 *haveAlphaP = false;
772 *haveAndP = false;
773 break;
774
775 case 4:
776 *getPixelP = get_rgbPixel;
777 if (realAlphaNeeded(pamP, tuples, 3)) {
778 *haveAlphaP = true;
779 *alphaPlaneP = 3;
780 *haveAndP = false;
781 } else {
782 *haveAlphaP = false;
783 *haveAndP = true;
784 *andPlaneP = 3;
785 }
786 break;
787
788 case 5:
789 *getPixelP = get_rgbPixel;
790 *haveAlphaP = true;
791 *alphaPlaneP = 3;
792 *haveAndP = true;
793 *andPlaneP = 4;
794 break;
795
796 default:
797 pm_error("unexpected PAM depth %u. "
798 "We understand depths 1-5", pamP->depth);
799 break;
800 }
801 }
802
803
804
805 static void
806 reportImageInfo(unsigned int const imageNum,
807 const struct pam * const pamP,
808 const struct Palette * const paletteP,
809 bool const haveAlpha,
810 bool const haveAnd) {
811
812 const char * colorCt;
813
814 if (paletteP->tooManyColors)
815 pm_asprintf(&colorCt, "> 256");
816 else
817 pm_asprintf(&colorCt, "%u", paletteP->colorCt);
818
819 pm_message("Image %2u:"
820 " %3u x %3u x %u, %s colors%s%s",
821 imageNum,
822 pamP->width, pamP->height, pamP->depth,
823 colorCt,
824 haveAlpha ? ", alpha channel": "",
825 haveAnd ? ", AND mask": "");
826
827 pm_strfree(colorCt);
828 }
829
830
831
832 static void
833 writeIconAndCreateDirEntry(const struct pam * const pamP,
834 tuple ** const tuples,
835 GetPixelFn * const getPixel,
836 bool const doingPng,
837 bool const haveAlpha,
838 unsigned int const alphaPlane,
839 bool const haveAnd,
840 unsigned int const andPlane,
841 bool const mustBlackenXor,
842 const struct Palette * const paletteP,
843 FILE * const ofP,
844 struct IconDirEntry * const dirEntryP) {
845 /*----------------------------------------------------------------------------
846 Write to *ofP the icon image for the image represented by *pamP and
847 'tuples'.
848
849 Generate the information for an icon directory entry for this image
850 and return it as *dirEntryP. ==>BUT: the 'offset' member of this
851 structure will not be meaningful. <==
852
853 Make a PNG image if 'doingPng' is true; BMP otherwise.
854
855 'haveAlpha' means that there is an alpha plane in 'tuples' and it is
856 Plane 'alphaPlane'.
857
858 'haveAnd' means that there is an AND plane in 'tuples' and it is Plane
859 'andPlane'.
860
861 *paletteP is the color palette for the icon; it contains an entry for each
862 color in 'tuples'. Except: it may simply indicate that there are too many
863 colors in 'tuples' to have a palette.
864
865 The 'bits_per_pixel' member of the directory entry is supposed to tell the
866 color resolution of the image so the user can decide which of many versions
867 of the icon in the file to use. But we just call it 32 bits in every case
868 except paletted BMP, where it actually relates to how many colors are in
869 the image.
870 -----------------------------------------------------------------------------*/
871 dirEntryP->width = pamP->width;
872 dirEntryP->height = pamP->height;
873 dirEntryP->color_planes = 1;
874 dirEntryP->zero = 0;
875
876 if (doingPng) {
877 dirEntryP->color_count = 0;
878 dirEntryP->bits_per_pixel = 32;
879
880 writePng(pamP, tuples, haveAlpha, alphaPlane, haveAnd, andPlane,
881 &dirEntryP->size, ofP);
882 } else {
883 uint32_t bmpSize;
884 uint32_t andMaskSize;
885
886 if (mustBlackenXor)
887 blackenXor(pamP, tuples,
888 haveAlpha, alphaPlane, haveAnd, andPlane);
889
890 if (haveAlpha) {
891 dirEntryP->color_count = 0;
892 dirEntryP->bits_per_pixel = 32;
893
894 write32BitBmp(pamP, tuples, getPixel, haveAlpha, alphaPlane,
895 ofP, &bmpSize);
896 } else if (paletteP->tooManyColors) {
897 /* Do a truecolor image */
898 dirEntryP->color_count = 0;
899 dirEntryP->bits_per_pixel = 32;
900
901 write32BitBmp(pamP, tuples, getPixel, false /*haveAlpha*/, 0,
902 ofP, &bmpSize);
903 } else {
904 /* Do a paletted image */
905
906 if (paletteP->colorCt <= 2) {
907 dirEntryP->color_count = paletteP->colorCt;
908 dirEntryP->bits_per_pixel = 1;
909
910 writePaletteBmp(1, pamP, tuples, getPixel, paletteP,
911 ofP, &bmpSize);
912 } else if (paletteP->colorCt <= 16) {
913 dirEntryP->color_count = paletteP->colorCt;
914 dirEntryP->bits_per_pixel = 4;
915
916 writePaletteBmp(4, pamP, tuples, getPixel,paletteP,
917 ofP, &bmpSize);
918 } else {
919 dirEntryP->color_count = 0;
920 dirEntryP->bits_per_pixel = 8;
921
922 writePaletteBmp(8, pamP, tuples, getPixel, paletteP,
923 ofP, &bmpSize);
924 }
925 }
926 writeAndMask(pamP, tuples, haveAlpha, alphaPlane, haveAnd, andPlane,
927 ofP, &andMaskSize);
928
929 dirEntryP->size = bmpSize + andMaskSize;
930 }
931 }
932
933
934
935 static void
936 convertOneImage(unsigned int const imageNum,
937 FILE * const ifP,
938 unsigned int const pngThreshold,
939 bool const mustBlackenXor,
940 FILE * const ofP,
941 struct IconDir * const dirP) {
942
943 struct IconDirEntry dirEntry;
944 struct pam pam;
945 tuple ** tuples;
946 bool haveAlpha;
947 unsigned int alphaPlane;
948 bool haveAnd;
949 unsigned int andPlane;
950 GetPixelFn * getPixel;
951 struct Palette palette;
952 bool doingPng;
953
954 /* Output:
955 *
956 * threshold^2 pixels or more:
957 * no alpha channel: PNG (RGB)
958 * alpha channel: PNG (RGBA)
959 * alpha channel +AND mask: PNG (RGBA), AND mask dropped
960 * alpha values other than 0 and maxval: 32bit +alpha BMP
961 * no more than 2 colors: 1bit or 32bit BMP
962 * no more than 16 colors: 4bit or 32bit BMP
963 * no more than 256 colors: 8bit or 32bit BMP
964 * more than 256 colors: 32bit BMP
965 */
966 pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
967
968 if (pam.width > 256 || pam.height > 256)
969 pm_error("Image %u: too large as a windows icon (%u x %u). "
970 "Maximum allowed dimension is 256",
971 imageNum, pam.width, pam.height);
972
973 tuples = pnm_allocpamarray(&pam);
974
975 doingPng = pam.width * pam.height >= pngThreshold;
976
977 if (verbose)
978 pm_message("Image %2u: encoding as %s",
979 imageNum, doingPng ? "PNG" : "BMP");
980
981 readAndScalePam(&pam, doingPng, tuples);
982
983 determineImageType(&pam, tuples, &getPixel,
984 &haveAlpha, &alphaPlane, &haveAnd, &andPlane);
985
986 getPalette(&pam, tuples, getPixel, &palette);
987
988 if (verbose)
989 reportImageInfo(imageNum, &pam, &palette, haveAlpha, haveAnd);
990
991 writeIconAndCreateDirEntry(&pam, tuples, getPixel, doingPng,
992 haveAlpha, alphaPlane,
993 haveAnd, andPlane,
994 mustBlackenXor,
995 &palette,
996 ofP, &dirEntry);
997
998 if (verbose)
999 pm_message("Image %2u: %u bytes", imageNum, dirEntry.size);
1000
1001 pnm_freepamarray(tuples, &pam);
1002
1003 addToDirectory(&dirEntry, dirP);
1004 }
1005
1006
1007
1008 static void
1009 convert(FILE * const ifP,
1010 unsigned int const pngThreshold,
1011 bool const mustBlackenXor,
1012 struct IconDir * const dirP,
1013 FILE * const ofP) {
1014 /*----------------------------------------------------------------------------
1015 Read a (multi-image) PAM file from *ifP and convert the individual images
1016 to the proper format for a Windows icon file and write those to *ofP.
1017
1018 Where the number of pixels in an image is at least 'pngThreshold', use
1019 a PNG image. Otherwise, use a BMP.
1020 -----------------------------------------------------------------------------*/
1021 unsigned int imageNum;
1022 int eof;
1023
1024 for (imageNum = 0, eof = false; !eof; ++imageNum) {
1025 convertOneImage(imageNum, ifP, pngThreshold, mustBlackenXor,
1026 ofP, dirP);
1027
1028 pnm_nextimage(ifP, &eof);
1029 }
1030 }
1031
1032
1033
1034 static void
1035 writeIconDirEntry(const struct IconDirEntry * const dirEntryP,
1036 FILE * const ofP) {
1037
1038 pm_writecharu (ofP, dirEntryP->width);
1039 pm_writecharu (ofP, dirEntryP->height);
1040 pm_writecharu (ofP, dirEntryP->color_count);
1041 pm_writecharu (ofP, dirEntryP->zero);
1042 pm_writelittleshortu (ofP, dirEntryP->color_planes);
1043 pm_writelittleshortu (ofP, dirEntryP->bits_per_pixel);
1044 pm_writelittlelongu (ofP, dirEntryP->size);
1045 pm_writelittlelongu (ofP, dirEntryP->offset);
1046 }
1047
1048
1049
1050 static void
1051 writeIconDirectory(const struct IconDir * const dirP,
1052 FILE * const ofP) {
1053 /*----------------------------------------------------------------------------
1054 Write to file *ofP the icon directory described by *dirP.
1055
1056 *dirP's image offset members are meaningless as input. We fill them in.
1057 -----------------------------------------------------------------------------*/
1058 uint32_t const hsize = 6 + dirP->count * 16;
1059
1060 unsigned int imageNum;
1061 unsigned int imageOffset;
1062
1063 pm_writelittleshortu(ofP, dirP->zero);
1064 pm_writelittleshortu(ofP, dirP->type);
1065 pm_writelittleshortu(ofP, dirP->count);
1066
1067 for (imageNum = 0, imageOffset = hsize;
1068 imageNum < dirP->count;
1069 ++imageNum) {
1070
1071 struct IconDirEntry * const dirEntryP = &dirP->entries[imageNum];
1072
1073 pm_message("image %2u: %3u x %3u x %2u",
1074 imageNum,
1075 dirEntryP->width,
1076 dirEntryP->height,
1077 dirEntryP->bits_per_pixel);
1078
1079 dirEntryP->offset = imageOffset;
1080
1081 writeIconDirEntry(dirEntryP, ofP);
1082
1083 imageOffset += dirEntryP->size;
1084 }
1085 }
1086
1087
1088
1089 static void
1090 copyFile(FILE * const ifP,
1091 FILE * const ofP) {
1092
1093 bool eof;
1094
1095 for (eof = false; !eof; ) {
1096 unsigned char buffer[1024];
1097 size_t bytesRead;
1098
1099 bytesRead = fread(buffer, 1, sizeof(buffer), ifP);
1100
1101 if (bytesRead == 0)
1102 eof = true;
1103 else {
1104 size_t bytesWritten;
1105
1106 bytesWritten = fwrite(buffer, 1, bytesRead, ofP);
1107
1108 if (bytesWritten < bytesRead)
1109 pm_error("Error writing to output file.");
1110 }
1111 }
1112 }
1113
1114
1115
1116 static void
1117 writeIconFile(const struct IconDir * const dirP,
1118 FILE * const imagesFileP,
1119 FILE * const ofP) {
1120 /*----------------------------------------------------------------------------
1121 Write a windows icon file.
1122
1123 *dirP is the icon directory to put in it.
1124
1125 *imagesFileP contains all the text of the icon images. The contents of
1126 this file go verbatim into the output.
1127 -----------------------------------------------------------------------------*/
1128 writeIconDirectory(dirP, ofP);
1129
1130 copyFile(imagesFileP, ofP);
1131 }
1132
1133
1134
1135 int
1136 main(int argc, const char *argv []) {
1137
1138 struct CmdlineInfo cmdline;
1139 FILE * ifP;
1140 FILE * imagesFileP;
1141 /* This is the file in which we collect the individual icon
1142 images to be copied later to the output.
1143 */
1144 struct IconDir * dirP;
1145
1146 pm_proginit(&argc, argv);
1147
1148 parseCommandLine(argc, argv, &cmdline);
1149
1150 verbose = cmdline.verbose;
1151
1152 /* The output icon file has directory information at the top that we
1153 can't know until we have looked at the input images. So as we pass
1154 through the input, we collect the directory information and generate
1155 the individual icon images and store them in *imageFileP. When we've
1156 been through all of the input, we write out the directory and then
1157 copy the images from *imageFileP to the output.
1158 */
1159
1160 dirP = newIconDir();
1161
1162 imagesFileP = pm_tmpfile();
1163
1164 ifP = pm_openr(cmdline.inputFileName);
1165
1166 convert(ifP, SQR(cmdline.pngthreshold), cmdline.truetransparent,
1167 dirP, imagesFileP);
1168
1169 rewind(imagesFileP);
1170
1171 writeIconFile(dirP, imagesFileP, stdout);
1172
1173 freeIconDir(dirP);
1174
1175 return 0;
1176 }
1177
1178
1179