1 /* ppmtopgm.c - convert a portable pixmap to a portable graymap
2 **
3 ** Copyright (C) 1989 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 "pm_c_util.h"
14 #include "ppm.h"
15 #include "pgm.h"
16 #include "lum.h"
17
18 static void
convertRaster(FILE * const ifP,unsigned int const cols,unsigned int const rows,pixval const maxval,int const format,pixel * const inputRow,gray * const outputRow,FILE * const ofP)19 convertRaster(FILE * const ifP,
20 unsigned int const cols,
21 unsigned int const rows,
22 pixval const maxval,
23 int const format,
24 pixel * const inputRow,
25 gray * const outputRow,
26 FILE * const ofP) {
27
28 unsigned int row;
29
30 for (row = 0; row < rows; ++row) {
31 ppm_readppmrow( ifP, inputRow, cols, maxval, format );
32 if (maxval <= 255) {
33 /* Use fast approximation to 0.299 r + 0.587 g + 0.114 b */
34 unsigned int col;
35 for (col = 0; col < cols; ++col)
36 outputRow[col] = (gray) ppm_fastlumin(inputRow[col]);
37 } else {
38 /* Can't use fast approximation, so fall back on floats. */
39 unsigned int col;
40 for (col = 0; col < cols; ++col)
41 outputRow[col] = ppm_luminosity(inputRow[col]);
42 }
43 pgm_writepgmrow(ofP, outputRow, cols, maxval, 0);
44 }
45 }
46
47
48
49 int
main(int argc,char * argv[])50 main(int argc, char *argv[]) {
51
52 FILE* ifP;
53 const char * inputFilespec;
54 int eof;
55
56 ppm_init( &argc, argv );
57
58 if (argc-1 > 1)
59 pm_error("The only argument is the (optional) input filename");
60
61 if (argc == 2)
62 inputFilespec = argv[1];
63 else
64 inputFilespec = "-";
65
66 ifP = pm_openr(inputFilespec);
67
68 eof = FALSE; /* initial assumption */
69
70 while (!eof) {
71 ppm_nextimage(ifP, &eof);
72 if (!eof) {
73 int rows, cols, format;
74 pixval maxval;
75 pixel* inputRow;
76 gray* outputRow;
77
78 ppm_readppminit(ifP, &cols, &rows, &maxval, &format);
79 pgm_writepgminit(stdout, cols, rows, maxval, 0);
80
81 inputRow = ppm_allocrow(cols);
82 outputRow = pgm_allocrow(cols);
83
84 convertRaster(ifP, cols, rows, maxval, format,
85 inputRow, outputRow, stdout);
86
87 ppm_freerow(inputRow);
88 pgm_freerow(outputRow);
89 }
90 }
91 pm_close(ifP);
92 pm_close(stdout);
93
94 return 0;
95 }
96