1 /* ppmtopuzz.c - read a portable pixmap and write an X11 "puzzle" file
2 **
3 ** Copyright (C) 1991 by Jef Poskanzer.
4 **
5 ** Permission to use, copy, modify, and distribute this software and its
6 ** documentation for any purpose and without fee is hereby granted, provided
7 ** that the above copyright notice appear in all copies and that both that
8 ** copyright notice and this permission notice appear in supporting
9 ** documentation. This software is provided "as is" without express or
10 ** implied warranty.
11 */
12
13 #include "ppm.h"
14
15 #define MAXVAL 255
16 #define MAXCOLORS 256
17
18 int
main(argc,argv)19 main( argc, argv )
20 int argc;
21 char* argv[];
22 {
23 FILE* ifp;
24 pixel** pixels;
25 register pixel* pP;
26 colorhist_vector chv;
27 colorhash_table cht;
28 int rows, cols, row, colors, i;
29 register int col;
30 pixval maxval;
31
32
33 ppm_init( &argc, argv );
34
35 if ( argc > 2 )
36 pm_usage( "[ppmfile]" );
37
38 if ( argc == 2 )
39 ifp = pm_openr( argv[1] );
40 else
41 ifp = stdin;
42
43 pixels = ppm_readppm( ifp, &cols, &rows, &maxval );
44 pm_close( ifp );
45
46 pm_message( "computing colormap..." );
47 chv = ppm_computecolorhist( pixels, cols, rows, MAXCOLORS, &colors );
48 if ( chv == (colorhist_vector) 0 )
49 {
50 pm_message(
51 "too many colors - try doing a 'pnmquant %d'", MAXCOLORS );
52 exit( 1 );
53 }
54 pm_message( "%d colors found", colors );
55
56 /* Write puzzle header. */
57 (void) pm_writebiglong( stdout, cols );
58 (void) pm_writebiglong( stdout, rows );
59 (void) putchar( (unsigned char) colors );
60 if ( maxval > MAXVAL )
61 pm_message(
62 "maxval is not %d - automatically rescaling colors", MAXVAL );
63 for ( i = 0; i < colors; ++i )
64 {
65 pixel p;
66
67 p = chv[i].color;
68 if ( maxval != MAXVAL )
69 PPM_DEPTH( p, p, maxval, MAXVAL );
70 (void) putchar( (unsigned char) PPM_GETR( p ) );
71 (void) putchar( (unsigned char) PPM_GETG( p ) );
72 (void) putchar( (unsigned char) PPM_GETB( p ) );
73 }
74
75 /* Convert color vector to color hash table, for fast lookup. */
76 cht = ppm_colorhisttocolorhash( chv, colors );
77 ppm_freecolorhist( chv );
78
79 /* And write out the data. */
80 for ( row = 0; row < rows; ++row )
81 {
82 for ( col = 0, pP = pixels[row]; col < cols; ++col, ++pP )
83 {
84 register int color;
85
86 color = ppm_lookupcolor( cht, pP );
87 if ( color == -1 )
88 pm_error(
89 "color not found?!? row=%d col=%d r=%d g=%d b=%d",
90 row, col, PPM_GETR(*pP), PPM_GETG(*pP), PPM_GETB(*pP) );
91 (void) putchar( (unsigned char) color );
92 }
93 }
94
95 exit( 0 );
96 }
97