about summary refs log tree commit diff
path: root/converter/ppm/rgb3toppm.c
blob: a666553c715420f0d688c5aa4d5e7cf6d4f49a6d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* rgb3toppm - combine three portable graymaps into one portable pixmap
**
** Copyright (C) 1991 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 "ppm.h"

int
main( argc, argv )
    int argc;
    char* argv[];
    {
    FILE* rfd;
    FILE* gfd;
    FILE* bfd;
    gray* rrow;
    gray* rP;
    gray* grow;
    gray* gP;
    gray* brow;
    gray* bP;
    pixel* pixelrow;
    register pixel* pP;
    int rows, cols, trows, tcols, row, col;
    gray rmaxval, gmaxval, bmaxval;
    int rformat, gformat, bformat;
    pixval pmaxval;


    ppm_init( &argc, argv );

    if ( argc != 4 )
	pm_usage( "<red pgmfile> <green pgmfile> <blue pgmfile> " );

    rfd = pm_openr( argv[1] );
    gfd = pm_openr( argv[2] );
    bfd = pm_openr( argv[3] );

    pgm_readpgminit( rfd, &cols, &rows, &rmaxval, &rformat );
    pgm_readpgminit( gfd, &tcols, &trows, &gmaxval, &gformat );
    if ( tcols != cols || trows != rows )
	pm_error( "all three graymaps must be the same size" );
    pgm_readpgminit( bfd, &tcols, &trows, &bmaxval, &bformat );
    if ( tcols != cols || trows != rows )
	pm_error( "all three graymaps must be the same size" );

    pmaxval = rmaxval;
    if ( gmaxval > pmaxval ) pmaxval = gmaxval;
    if ( bmaxval > pmaxval ) pmaxval = bmaxval;
    rrow = pgm_allocrow( cols );
    grow = pgm_allocrow( cols );
    brow = pgm_allocrow( cols );

    ppm_writeppminit( stdout, cols, rows, pmaxval, 0 );
    pixelrow = ppm_allocrow( cols );

    for ( row = 0; row < rows; row++ )
	{
	pgm_readpgmrow( rfd, rrow, cols, rmaxval, rformat );
	pgm_readpgmrow( gfd, grow, cols, gmaxval, gformat );
	pgm_readpgmrow( bfd, brow, cols, bmaxval, bformat );

	for ( col = 0, rP = rrow, gP = grow, bP = brow, pP = pixelrow;
	      col < cols;
	      ++col, ++rP, ++gP, ++bP, ++pP )
	    {
	    if ( rmaxval != pmaxval ) *rP = (int) *rP * pmaxval / rmaxval;
	    if ( gmaxval != pmaxval ) *gP = (int) *gP * pmaxval / gmaxval;
	    if ( bmaxval != pmaxval ) *bP = (int) *bP * pmaxval / bmaxval;
	    PPM_ASSIGN( *pP, *rP, *gP, *bP );
	    }
	ppm_writeppmrow( stdout, pixelrow, cols, pmaxval, 0 );
	}

    pm_close( rfd );
    pm_close( gfd );
    pm_close( bfd );
    pm_close( stdout );

    exit( 0 );
    }