IPGM.c
资源名称:ilib [点击查看]
上传用户:changbiao
上传日期:2007-01-13
资源大小:141k
文件大小:2k
源码类别:

图片显示

开发平台:

C/C++

  1. /*
  2.  * IPPMC.c
  3.  *
  4.  * Image library
  5.  *
  6.  * Description:
  7.  * PGM routines.  PGM is 8-bit grayscale.
  8.  *
  9.  * History:
  10.  * 23-Jul-99 Craig Knudsen cknudsen@radix.net
  11.  * Created
  12.  *
  13.  ****************************************************************************/
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <memory.h>
  18. #include "Ilib.h"
  19. #include "IlibP.h"
  20. IError _IWritePGM ( fp, image, options )
  21. FILE *fp;
  22. IImageP *image;
  23. IOptions options;
  24. {
  25.   int r, c;
  26.   unsigned char *ptr;
  27.   unsigned int val, red, green, blue;
  28.   if ( options & IOPTION_ASCII ) {
  29.     fprintf ( fp, "P2n" );
  30.     if ( image->comments )
  31.       fprintf ( fp, "# %sn", image->comments );
  32.     fprintf ( fp, "%d %dn255n", image->width, image->height );
  33.     for ( r = 0; r < image->height; r++ ) {
  34.       for ( c = 0; c < image->width; c++ ) {
  35.         if ( image->greyscale ) {
  36.           ptr = image->data + ( r * image->width ) + c;
  37.           val = (unsigned int) *ptr;
  38.         }
  39.         else {
  40.           ptr = image->data + ( r * image->width * 3 ) + ( c * 3 );
  41.           red = (unsigned int) *ptr;
  42.           green = (unsigned int) *( ptr + 1 );
  43.           blue = (unsigned int) *( ptr + 2 );
  44.           val = ( red + green + blue ) / 3;
  45.         }
  46.         fprintf ( fp, "%dn", val );
  47.       }
  48.     }
  49.   }
  50.   else {
  51.     fprintf ( fp, "P5n" );
  52.     if ( image->comments )
  53.       fprintf ( fp, "# %sn", image->comments );
  54.     fprintf ( fp, "%d %dn255n", image->width, image->height );
  55.     if ( image->greyscale ) {
  56.       if ( fwrite ( image->data, 1, image->width * image->height, fp ) <= 0 )
  57.         return ( IErrorWriting );
  58.     } else {
  59.       for ( r = 0; r < image->height; r++ ) {
  60.         for ( c = 0; c < image->width; c++ ) {
  61.           ptr = image->data + ( r * image->width * 3 ) + ( c * 3 );
  62.           red = (unsigned int) *ptr;
  63.           green = (unsigned int) *( ptr + 1 );
  64.           blue = (unsigned int) *( ptr + 2 );
  65.           val = ( red + green + blue ) / 3;
  66.           if ( fwrite ( &val, 1, 1, fp ) <= 0 )
  67.             return ( IErrorWriting );
  68.         }
  69.       }
  70.     }
  71.   }
  72.   return ( INoError );
  73. }
  74. /* NOTE: There is no _IReadPGM().  We use _ReadPPM() instead since it
  75.  *       can handle both PPM and PGM.
  76.  */