232 unsigned pixel_shift=1;
233 unsigned pgm_format=0;
242 for(i = 1; i < (unsigned)argc; i++) {
243 if (
strncmp(argv[i],
"-h=",3) == 0 ) {
244 height=
atoi(argv[i]+3);
246 else if (
strncmp(argv[i],
"-w=",3) == 0 ) {
247 width=
atoi(argv[i]+3);
249 else if (
strcmp(argv[i],
"-noshift") == 0 ) {
252 else if(
strcmp(argv[i],
"-pgm") == 0 ) {
255 else if ( argv[i][0]==
'-' ) {
256 if( !(op =
find_op(argv[i]+1))) {
257 fprintf(stderr,
"%s: unknown option %s\n",argv[0],argv[i]);
269 fprintf(stderr,
"%s: unknown option %s\n",argv[0],argv[i]);
275 fprintf(stderr,
"%s: missing input file\n",argv[0]);
279 fprintf(stderr,
"%s: missing output file\n",argv[0]);
283 fprintf(stderr,
"%s: no op given\n",argv[0]);
286 if(!height || !width) {
287 fprintf(stderr,
"%s: invalid dimensions\n",argv[0]);
291 if(
stat(iname,&st) != 0) {
292 fprintf(stderr,
"%s: bad input file %s\n",argv[0],iname);
296 if((width*op->
ibpp)%8 != 0) {
297 fprintf(stderr,
"WARNING: width %u not an integral number of bytes at %u bpp\n",width,op->
ibpp);
299 if((width*op->
obpp)%8 != 0) {
300 fprintf(stderr,
"WARNING: width %u not an integral number of bytes at %u bpp\n",width,op->
obpp);
302 if(pgm_format && op->
obpp!=8 && op->
obpp!=16) {
303 fprintf(stderr,
"WARNING: Portable Gray Map (PGM) format supports only 8 or 16 bpp.\n");
307 in_data=
malloc(st.st_size);
310 fp=
fopen(iname,
"rb");
313 rcount=
fread(in_data,1,st.st_size,fp);
314 assert(rcount==(
size_t)st.st_size);
318 npixels=height*
width;
319 if((npixels*op->
ibpp) >> 3 != st.st_size) {
320 fprintf(stderr,
"%s: %s mismatched size (%u*%u*%u)/8 -> %u != %u\n",
321 argv[0], iname, width, height, op->
ibpp, (npixels*op->
ibpp) >> 3, (
unsigned)st.st_size);
324 osize = (npixels*op->
obpp) >> 3;
328 fprintf(stderr,
"input: %s %ux%u %u bpp %u bytes\n",iname, width, height, op->
ibpp, (
unsigned)(st.st_size));
329 fprintf(stderr,
"output: %s %u bpp %u bytes\n", oname, op->
obpp, osize);
334 fprintf(stderr,
" discard lower %d bits\n",-bpp_diff);
336 fprintf(stderr,
" multiply pixel values %d\n",1 << bpp_diff);
338 else if(bpp_diff < 0) {
339 fprintf(stderr,
" discard upper %d bits\n",-bpp_diff);
343 unsigned pixel_value;
344 unsigned in_row_bytes=(width*op->
ibpp)>>3;
345 unsigned out_row_bytes=(width*op->
obpp)>>3;
346 for(i=0; i<npixels; i++) {
347 pixel_value = op->
get_pixel(in_data, in_row_bytes, i%width, i/width);
350 pixel_value >>= -bpp_diff;
352 else if (bpp_diff > 0) {
353 pixel_value <<= bpp_diff;
356 op->
set_pixel(out_data, out_row_bytes, i%width, i/width, pixel_value);
360 fp=
fopen(oname,
"wb");
364 fprintf(fp,
"P5\n%d\n%d\n%d\n", width, height, (1 << op->
obpp)-1);
367 fwrite(out_data, 1, osize, fp);
372 fprintf(stderr,
"done\n");