home *** CD-ROM | disk | FTP | other *** search
- /* pbmcut.c - cut a rectangle out of 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;
- int rows, cols, x, y, width, height, row, col;
- char *usage = "usage: %s x y width height [pbmfile]\n";
-
-
- if ( argc < 5 || argc > 6 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
-
- if ( sscanf( argv[1], "%d", &x ) != 1 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
- if ( sscanf( argv[2], "%d", &y ) != 1 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
- if ( sscanf( argv[3], "%d", &width ) != 1 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
- if ( sscanf( argv[4], "%d", &height ) != 1 )
- {
- fprintf( stderr, usage, argv[0] );
- exit( 1 );
- }
-
- if ( x < 0 )
- {
- fprintf( stderr, "x is less than 0\n" );
- exit( 1 );
- }
- if ( y < 0 )
- {
- fprintf( stderr, "y is less than 0\n" );
- exit( 1 );
- }
- if ( width < 1 )
- {
- fprintf( stderr, "width is less than 1\n" );
- exit( 1 );
- }
- if ( height < 1 )
- {
- fprintf( stderr, "height is less than 1\n" );
- exit( 1 );
- }
-
- if ( argc == 6 )
- {
- ifd = fopen( argv[5], "r" );
- if ( ifd == NULL )
- {
- fprintf( stderr, "%s: can't open.\n", argv[5] );
- exit( 1 );
- }
- }
- else
- ifd = stdin;
-
- bits = pbm_readpbm( ifd, &cols, &rows );
-
- if ( ifd != stdin )
- fclose( ifd );
-
- if ( x >= cols )
- {
- fprintf(
- stderr, "x is too large -- the bitmap has only %d cols\n", cols );
- exit( 1 );
- }
- if ( y >= rows )
- {
- fprintf(
- stderr, "y is too large -- the bitmap has only %d rows\n", rows );
- exit( 1 );
- }
- if ( x + width > cols )
- {
- fprintf(
- stderr, "x + width is too large by %d pixels\n", x + width - cols );
- exit( 1 );
- }
- if ( y + height > rows )
- {
- fprintf(
- stderr, "y + height is too large by %d pixels\n",
- y + height - rows );
- exit( 1 );
- }
-
- newbits = pbm_allocarray( width, height );
- for ( row = y; row < y + height; row++ )
- for ( col = x; col < x + width; col++ )
- newbits[row-y][col-x] = bits[row][col];
-
- pbm_writepbm( stdout, newbits, width, height );
-
- exit( 0 );
- }
-