home *** CD-ROM | disk | FTP | other *** search
- /* pbmcrop.c - crop a portable bitmap
- **
- ** Copyright (C) 1988 by Jef Poskanzer.
- **
- ** Permission to use, copy, modify, and distribute this software and its
- ** documentation for any purpose and without fee is hereby granted, provided
- ** that the above copyright notice appear in all copies and that both that
- ** copyright notice and this permission notice appear in supporting
- ** documentation. This software is provided "as is" without express or
- ** implied warranty.
- */
-
- #include <stdio.h>
- #include "pbm.h"
-
- main( argc, argv )
- int argc;
- char *argv[];
- {
- FILE *ifd;
- bit **bits, **newbits, background;
- int argn, backdefault, c;
- int rows, cols, row, col, newrows, newcols;
- int top, bottom, left, right;
- char *usage = "usage: %s [-0] [-1] [pbmfile]\n";
-
- argn = 1;
- backdefault = 1;
-
- /* Check for flags. */
- if ( argc > argn )
- {
- if ( argv[argn][0] == '-' )
- {
- if ( strcmp( argv[argn], "-0" ) == 0 )
- {
- backdefault = 0;
- background = 0;
- argn++;
- }
- else if ( strcmp( argv[argn], "-1" ) == 0 )
- {
- backdefault = 0;
- background = 1;
- argn++;
- }
- else
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
- }
- }
-
- if ( argc > argn + 1 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
-
- if ( argc == argn + 1 )
- {
- ifd = fopen( argv[argn], "r" );
- if ( ifd == NULL )
- {
- fprintf( stderr, "%s: can't open.\n", argv[argn] );
- exit( 1 );
- }
- }
- else
- ifd = stdin;
-
- bits = pbm_readpbm( ifd, &cols, &rows );
-
- if ( ifd != stdin )
- fclose( ifd );
-
- if ( backdefault )
- {
- /* Make a reasonable guess as to what the background is. */
- c = (int) bits[0][0] + (int) bits[0][cols-1] +
- (int) bits[rows-1][0] + (int) bits[rows-1][cols-1];
- background = ( c <= 2 ) ? 0 : 1;
- }
-
- /* Find first non-background line. */
- for ( top = 0; top < rows; top++ )
- for ( col = 0; col < cols; col++ )
- if ( bits[top][col] != background )
- goto gottop;
- gottop:
-
- /* Find last non-background line. */
- for ( bottom = rows-1; bottom >= top; bottom-- )
- for ( col = 0; col < cols; col++ )
- if ( bits[bottom][col] != background )
- goto gotbottom;
- gotbottom:
-
- /* Find first non-background column. */
- for ( left = 0; left < cols; left++ )
- for ( row = top; row < bottom; row++ )
- if ( bits[row][left] != background )
- goto gotleft;
- gotleft:
-
- /* Find last non-background column. */
- for ( right = cols-1; right > left; right-- )
- for ( row = top; row <= bottom; row++ )
- if ( bits[row][right] != background )
- goto gotright;
- gotright:
-
- /* Now copy into a new array. */
- newcols = right - left + 1;
- newrows = bottom - top + 1;
- newbits = pbm_allocarray( newcols, newrows );
- for ( row = top; row <= bottom; row++ )
- for ( col = left; col <= right; col++ )
- newbits[row-top][col-left] = bits[row][col];
-
- pbm_writepbm( stdout, newbits, newcols, newrows );
-
- exit( 0 );
- }
-