00001 #include "sadie.h"
00002
00003 #define UCHAR(c) ((unsigned char) (c))
00004
00005
00006
00007
00008
00009
00010 #define MAX_MEMORY 10000
00011
00012
00013
00014
00015
00016 #define PGM 1
00017 #define PPM 2
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 void
00029 IMG2PNM (in, name)
00030 IMAGE *in;
00031 char *name;
00032
00033 {
00034 int i, j, k;
00035 char msg[SLEN];
00036 FILE *fp = NULL;
00037 int nBytes, nbit = 8;
00038 unsigned char *pixelPtr = NULL, *data = NULL;
00039 char header[30];
00040 int count;
00041 PIXEL factor;
00042 char type[5];
00043 int nbnd;
00044
00045
00046 if (!(fp = fopen (name, "w")))
00047 {
00048 sprintf (msg, " Can't open file %s.", name);
00049 MESSAGE ('E', msg);
00050 goto the_end;
00051 }
00052
00053 if (!CHECKIMG (in))
00054 {
00055 MESSAGE ('E', " Can't identify image.");
00056 goto the_end;
00057 }
00058
00059 if (NAMES)
00060 {
00061 MESSAGE ('I', "");
00062 MESSAGE ('I', "IMG2PNM");
00063 MESSAGE ('I', "");
00064 sprintf (msg, " Input image: %s", in->text);
00065 MESSAGE ('I', msg);
00066 sprintf (msg, " Output disk file: %s", name);
00067 MESSAGE ('I', msg);
00068 sprintf (msg, " Output format: %d-bit PNM", nbit);
00069 MESSAGE ('I', msg);
00070 MESSAGE ('I', " ...............");
00071 }
00072
00073 RANGE (in);
00074 if (in->gmax > in->gmin)
00075 {
00076 factor = (PIXEL) 255.0 / (in->gmax - in->gmin);
00077 }
00078
00079 if (in->nbnd == 3)
00080 {
00081 nbnd = 3;
00082 sprintf (type, "P6");
00083 }
00084 else
00085 {
00086 nbnd = 1;
00087 sprintf (type, "P5");
00088 }
00089
00090 sprintf (header, "%s\n%d %d\n255\n", type, in->npix, in->nlin);
00091 nBytes = strlen (header);
00092 count = fwrite (header, 1, nBytes, fp);
00093 if (count != nBytes)
00094 {
00095 MESSAGE ('E', "Can't write header to file.");
00096 goto the_end;
00097 }
00098
00099 nBytes = in->npix * nbnd;
00100 pixelPtr = (unsigned char *) malloc ((unsigned) nBytes);
00101 if (!pixelPtr)
00102 {
00103 MESSAGE ('E', "Could not allocate memory to write image.");
00104 goto the_end;
00105 }
00106
00107 for (j = 0; j < in->nlin; j++)
00108 {
00109 data = pixelPtr;
00110
00111 for (k = 0; k < in->npix; k++)
00112 {
00113 for (i = 0; i < nbnd; i++)
00114 {
00115 *data++ = (unsigned char) rnd (in->data[i][j][k] * factor);
00116 }
00117 }
00118
00119 count = fwrite (pixelPtr, 1, nBytes, fp);
00120 if (count != nBytes)
00121 {
00122 sprintf (msg, "Error writing PNM image data to file");
00123 MESSAGE ('E', msg);
00124 goto the_end;
00125 }
00126 }
00127
00128 the_end:
00129
00130 if (pixelPtr)
00131 free (pixelPtr);
00132
00133 if (fp)
00134 {
00135 if (fclose (fp))
00136 {
00137 sprintf (msg, " Can't close file %s.", name);
00138 MESSAGE ('W', msg);
00139 }
00140 }
00141
00142 }