1
/****************************************************************************
2
pnm.c - read and write pnm images using libpnm/netpbm routines.
3
Distributed with Xplanet.
4
Copyright (C) 2002 Hari Nair <hari@alumni.caltech.edu>
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
GNU General Public License for more details.
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
****************************************************************************/
27
read_pnm(const char *filename, int *width, int *height, char **rgb)
29
FILE *infile = fopen(filename, "rb");
41
argv = malloc(sizeof(char **));
44
fprintf(stderr, "Can't allocate memory in read_pnm().\n");
51
fprintf(stderr, "Can't allocate memory in read_pnm().\n");
55
strcpy(argv[0], "loadimage");
57
pnm_init(&argcP, argv);
59
imagearray = pnm_readpnm(infile, width, height, &maxvalP, &formatP);
61
rgb[0] = malloc(3 * *width * *height);
64
fprintf(stderr, "Can't allocate memory for PNM file.\n");
68
switch (PNM_FORMAT_TYPE(formatP))
71
for (j = 0; j < *height; j++)
72
for (i = 0; i < *width; i++)
74
rgb[0][ipos++] = (unsigned char) (PPM_GETR(imagearray[j][i])
76
rgb[0][ipos++] = (unsigned char) (PPM_GETG(imagearray[j][i])
78
rgb[0][ipos++] = (unsigned char) (PPM_GETB(imagearray[j][i])
84
for (j = 0; j < *height; j++)
85
for (i = 0; i < *width; i++)
88
(unsigned char) (PNM_GET1(imagearray[j][i]) & 0xff),
94
fprintf(stderr, "Unknown magic number for pnm file\n");
98
pnm_freearray(imagearray, *height);
103
write_pnm(FILE *outfile, int width, int height, unsigned char *rgb,
104
int maxv, int format, int forceplain)
106
xelval maxval = maxv;
107
xel **imagearray = pnm_allocarray(width, height);
114
for (j = 0; j < height; j++)
117
for (i = 0; i < width; i++)
119
avg = (rgb[3 * (ipos + i)] + rgb[3 * (ipos + i) + 1]
120
+ rgb[3 * (ipos + i) + 2]) / 3;
121
PNM_ASSIGN1(imagearray[j][i], (avg > 127 ? 1 : 0));
126
for (j = 0; j < height; j++)
129
for (i = 0; i < width; i++)
131
avg = (rgb[3 * (ipos + i)] + rgb[3 * (ipos + i) + 1]
132
+ rgb[3 * (ipos + i) + 2]) / 3;
133
PNM_ASSIGN1(imagearray[j][i], avg);
138
for (j = 0; j < height; j++)
141
for (i = 0; i < width; i++)
143
PPM_ASSIGN(imagearray[j][i],
144
(xelval) rgb[3 * (ipos + i)],
145
(xelval) rgb[3 * (ipos + i) + 1],
146
(xelval) rgb[3 * (ipos + i) + 2]);
151
fprintf(stderr, "Unknown pnm format\n");
154
pnm_writepnm(outfile, imagearray, width, height, maxval, format,
157
pnm_freearray(imagearray, height);