static int ppm_getrawsample(int fd, int const maxval) { if (maxval < 256) { /* The sample is just one byte. Read it. */ return(ppm_getrawbyte(fd)); } else { /* The sample is two bytes. Read both. */ unsigned char byte_pair[2]; if (rb->read(fd, byte_pair, 2) < 2) { ppm_error("EOF. Read error while reading a long sample."); return PLUGIN_ERROR; } return((byte_pair[0]<<8) | byte_pair[1]); } }
/* Read PPM file */ unsigned char* ppm_read(FILE* file,int& cols,int& rows){ unsigned char* pixels,*pix; unsigned int r,g,b; int format,maxval; int row,col; /* Get format */ format=ppm_readmagicnumber(file); /* Get size */ cols=ppm_getint(file); rows=ppm_getint(file); maxval=ppm_getint(file); if(maxval<=0 || maxval>1023){ fprintf(stderr,"Illegal maxval value: %d.\n",maxval); exit(1); } /* Create memory */ pixels=(unsigned char*)malloc(3*rows*cols); if(!pixels){ fprintf(stderr,"Image too big\n"); exit(1); } /* Load pixels */ pix=pixels; switch(format){ case PPM_FORMAT: for(row=0; row<rows; row++){ for(col=0; col<cols; col++){ r = (255*ppm_getint(file))/maxval; g = (255*ppm_getint(file))/maxval; b = (255*ppm_getint(file))/maxval; *pix++ = r; *pix++ = g; *pix++ = b; } } break; case RPPM_FORMAT: for(row=0; row<rows; row++){ for(col=0; col<cols; col++){ r = ppm_getrawbyte(file); g = ppm_getrawbyte(file); b = ppm_getrawbyte(file); *pix++ = r; *pix++ = g; *pix++ = b; } } break; default: fprintf(stderr,"Unknown format.\n"); exit(1); break; } return pixels; }