pnm2png.c 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  pnm2png.c --- conversion from PBM/PGM/PPM-file to PNG-file
 *  copyright (C) 1999 by Willem van Schaik <willem@schaik.com>
 *
 *  version 1.0 - 1999.10.15 - First version.
 *
 *  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 <stdlib.h>
#ifdef __TURBOC__
#include <mem.h>
#include <fcntl.h>
#endif
21
#include <zlib.h>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

#ifndef BOOL
#define BOOL unsigned char
#endif
#ifndef TRUE
#define TRUE (BOOL) 1
#endif
#ifndef FALSE
#define FALSE (BOOL) 0
#endif

#define STDIN  0
#define STDOUT 1
#define STDERR 2

/* to make pnm2png verbose so we can find problems (needs to be before png.h) */
#ifndef PNG_DEBUG
#define PNG_DEBUG 0
#endif

#include "png.h"

44 45 46 47 48
/* Define png_jmpbuf() in case we are using a pre-1.0.6 version of libpng */
#ifndef png_jmpbuf
#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
#endif

49 50 51 52
/* function prototypes */

int  main (int argc, char *argv[]);
void usage ();
53 54
BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace,
    BOOL alpha);
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
void get_token(FILE *pnm_file, char *token);
png_uint_32 get_data (FILE *pnm_file, int depth);
png_uint_32 get_value (FILE *pnm_file, int depth);

/*
 *  main
 */

int main(int argc, char *argv[])
{
  FILE *fp_rd = stdin;
  FILE *fp_al = NULL;
  FILE *fp_wr = stdout;
  BOOL interlace = FALSE;
  BOOL alpha = FALSE;
  int argi;

  for (argi = 1; argi < argc; argi++)
  {
74
    if (argv[argi][0] == '-')
75
    {
76
      switch (argv[argi][1])
77 78 79 80 81 82 83 84 85 86
      {
        case 'i':
          interlace = TRUE;
          break;
        case 'a':
          alpha = TRUE;
          argi++;
          if ((fp_al = fopen (argv[argi], "rb")) == NULL)
          {
            fprintf (stderr, "PNM2PNG\n");
87 88
            fprintf (stderr, "Error:  alpha-channel file %s does not exist\n",
               argv[argi]);
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
            exit (1);
          }
          break;
        case 'h':
        case '?':
          usage();
          exit(0);
          break;
        default:
          fprintf (stderr, "PNM2PNG\n");
          fprintf (stderr, "Error:  unknown option %s\n", argv[argi]);
          usage();
          exit(1);
          break;
      } /* end switch */
    }
    else if (fp_rd == stdin)
    {
      if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
      {
        fprintf (stderr, "PNM2PNG\n");
        fprintf (stderr, "Error:  file %s does not exist\n", argv[argi]);
        exit (1);
      }
    }
    else if (fp_wr == stdout)
    {
      if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
      {
        fprintf (stderr, "PNM2PNG\n");
        fprintf (stderr, "Error:  can not create PNG-file %s\n", argv[argi]);
        exit (1);
      }
    }
    else
    {
      fprintf (stderr, "PNM2PNG\n");
      fprintf (stderr, "Error:  too many parameters\n");
      usage();
      exit (1);
    }
  } /* end for */

#ifdef __TURBOC__
  /* set stdin/stdout to binary, we're reading the PNM always! in binary format */
  if (fp_rd == stdin)
  {
    setmode (STDIN, O_BINARY);
  }
  if (fp_wr == stdout)
  {
    setmode (STDOUT, O_BINARY);
  }
#endif

  /* call the conversion program itself */
  if (pnm2png (fp_rd, fp_wr, fp_al, interlace, alpha) == FALSE)
  {
    fprintf (stderr, "PNM2PNG\n");
    fprintf (stderr, "Error:  unsuccessful converting to PNG-image\n");
    exit (1);
  }

  /* close input file */
  fclose (fp_rd);
  /* close output file */
  fclose (fp_wr);
  /* close alpha file */
  if (alpha)
    fclose (fp_al);

  return 0;
}

/*
 *  usage
 */

void usage()
{
  fprintf (stderr, "PNM2PNG\n");
  fprintf (stderr, "   by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
  fprintf (stderr, "   for Turbo-C and Borland-C compilers\n");
#else
  fprintf (stderr, "   for Linux (and Unix) compilers\n");
#endif
  fprintf (stderr, "Usage:  pnm2png [options] <file>.<pnm> [<file>.png]\n");
  fprintf (stderr, "   or:  ... | pnm2png [options]\n");
  fprintf (stderr, "Options:\n");
  fprintf (stderr, "   -i[nterlace]   write png-file with interlacing on\n");
180 181
  fprintf (stderr,
      "   -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
182 183 184 185 186 187 188
  fprintf (stderr, "   -h | -?  print this help-information\n");
}

/*
 *  pnm2png
 */

189 190
BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace,
     BOOL alpha)
191 192 193 194 195 196
{
  png_struct    *png_ptr = NULL;
  png_info      *info_ptr = NULL;
  png_byte      *png_pixels = NULL;
  png_byte      **row_pointers = NULL;
  png_byte      *pix_ptr = NULL;
197
  volatile png_uint_32   row_bytes;
198 199 200 201 202

  char          type_token[16];
  char          width_token[16];
  char          height_token[16];
  char          maxval_token[16];
203
  volatile int           color_type;
204 205 206
  unsigned long   ul_width=0, ul_alpha_width=0;
  unsigned long   ul_height=0, ul_alpha_height=0;
  unsigned long   ul_maxval=0;
207 208
  volatile png_uint_32   width, height;
  volatile png_uint_32   alpha_width, alpha_height;
209
  png_uint_32   maxval;
210
  volatile int           bit_depth = 0;
211 212 213 214 215
  int           channels;
  int           alpha_depth = 0;
  int           alpha_present;
  int           row, col;
  BOOL          raw, alpha_raw = FALSE;
216
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
217
  BOOL          packed_bitmap = FALSE;
218
#endif
219 220 221 222 223 224 225 226 227 228 229 230
  png_uint_32   tmp16;
  int           i;

  /* read header of PNM file */

  get_token(pnm_file, type_token);
  if (type_token[0] != 'P')
  {
    return FALSE;
  }
  else if ((type_token[1] == '1') || (type_token[1] == '4'))
  {
231
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
232 233
    raw = (type_token[1] == '4');
    color_type = PNG_COLOR_TYPE_GRAY;
234 235 236 237 238 239
    get_token(pnm_file, width_token);
    sscanf (width_token, "%lu", &ul_width);
    width = (png_uint_32) ul_width;
    get_token(pnm_file, height_token);
    sscanf (height_token, "%lu", &ul_height);
    height = (png_uint_32) ul_height;
240
    bit_depth = 1;
241
    packed_bitmap = TRUE;
242 243 244 245
#else
    fprintf (stderr, "PNM2PNG built without PNG_WRITE_INVERT_SUPPORTED and \n");
    fprintf (stderr, "PNG_WRITE_PACK_SUPPORTED can't read PBM (P1,P4) files\n");
#endif
246 247 248 249 250 251
  }
  else if ((type_token[1] == '2') || (type_token[1] == '5'))
  {
    raw = (type_token[1] == '5');
    color_type = PNG_COLOR_TYPE_GRAY;
    get_token(pnm_file, width_token);
252 253
    sscanf (width_token, "%lu", &ul_width);
    width = (png_uint_32) ul_width;
254
    get_token(pnm_file, height_token);
255 256
    sscanf (height_token, "%lu", &ul_height);
    height = (png_uint_32) ul_height;
257
    get_token(pnm_file, maxval_token);
258 259
    sscanf (maxval_token, "%lu", &ul_maxval);
    maxval = (png_uint_32) ul_maxval;
260

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    if (maxval <= 1)
      bit_depth = 1;
    else if (maxval <= 3)
      bit_depth = 2;
    else if (maxval <= 15)
      bit_depth = 4;
    else if (maxval <= 255)
      bit_depth = 8;
    else /* if (maxval <= 65535) */
      bit_depth = 16;
  }
  else if ((type_token[1] == '3') || (type_token[1] == '6'))
  {
    raw = (type_token[1] == '6');
    color_type = PNG_COLOR_TYPE_RGB;
    get_token(pnm_file, width_token);
277 278
    sscanf (width_token, "%lu", &ul_width);
    width = (png_uint_32) ul_width;
279
    get_token(pnm_file, height_token);
280 281
    sscanf (height_token, "%lu", &ul_height);
    height = (png_uint_32) ul_height;
282
    get_token(pnm_file, maxval_token);
283 284
    sscanf (maxval_token, "%lu", &ul_maxval);
    maxval = (png_uint_32) ul_maxval;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    if (maxval <= 1)
      bit_depth = 1;
    else if (maxval <= 3)
      bit_depth = 2;
    else if (maxval <= 15)
      bit_depth = 4;
    else if (maxval <= 255)
      bit_depth = 8;
    else /* if (maxval <= 65535) */
      bit_depth = 16;
  }
  else
  {
    return FALSE;
  }

  /* read header of PGM file with alpha channel */

  if (alpha)
  {
    if (color_type == PNG_COLOR_TYPE_GRAY)
      color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
    if (color_type == PNG_COLOR_TYPE_RGB)
      color_type = PNG_COLOR_TYPE_RGB_ALPHA;

    get_token(alpha_file, type_token);
    if (type_token[0] != 'P')
    {
      return FALSE;
    }
    else if ((type_token[1] == '2') || (type_token[1] == '5'))
    {
      alpha_raw = (type_token[1] == '5');
      get_token(alpha_file, width_token);
319 320
      sscanf (width_token, "%lu", &ul_alpha_width);
      alpha_width=(png_uint_32) ul_alpha_width;
321 322 323
      if (alpha_width != width)
        return FALSE;
      get_token(alpha_file, height_token);
324 325
      sscanf (height_token, "%lu", &ul_alpha_height);
      alpha_height = (png_uint_32) ul_alpha_height;
326 327 328
      if (alpha_height != height)
        return FALSE;
      get_token(alpha_file, maxval_token);
329 330
      sscanf (maxval_token, "%lu", &ul_maxval);
      maxval = (png_uint_32) ul_maxval;
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      if (maxval <= 1)
        alpha_depth = 1;
      else if (maxval <= 3)
        alpha_depth = 2;
      else if (maxval <= 15)
        alpha_depth = 4;
      else if (maxval <= 255)
        alpha_depth = 8;
      else /* if (maxval <= 65535) */
        alpha_depth = 16;
      if (alpha_depth != bit_depth)
        return FALSE;
    }
    else
    {
      return FALSE;
    }
  } /* end if alpha */

  /* calculate the number of channels and store alpha-presence */
  if (color_type == PNG_COLOR_TYPE_GRAY)
    channels = 1;
  else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
    channels = 2;
  else if (color_type == PNG_COLOR_TYPE_RGB)
    channels = 3;
  else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
    channels = 4;
  else
    channels = 0; /* should not happen */

  alpha_present = (channels - 1) % 2;

364
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
365 366 367 368
  if (packed_bitmap)
    /* row data is as many bytes as can fit width x channels x bit_depth */
    row_bytes = (width * channels * bit_depth + 7) / 8;
  else
369
#endif
370 371
    /* row_bytes is the width x number of channels x (bit-depth / 8) */
    row_bytes = width * channels * ((bit_depth <= 8) ? 1 : 2);
372

373 374
  if ((png_pixels = (png_byte *)
     malloc (row_bytes * height * sizeof (png_byte))) == NULL)
375 376 377 378 379
    return FALSE;

  /* read data from PNM file */
  pix_ptr = png_pixels;

380
  for (row = 0; row < (int) height; row++)
381
  {
382
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
383
    if (packed_bitmap) {
384
      for (i = 0; i < (int) row_bytes; i++)
385 386
        /* png supports this format natively so no conversion is needed */
        *pix_ptr++ = get_data (pnm_file, 8);
387 388 389
    } else
#endif
    {
390
      for (col = 0; col < (int) width; col++)
391
      {
392 393 394 395
        for (i = 0; i < (channels - alpha_present); i++)
        {
          if (raw)
            *pix_ptr++ = get_data (pnm_file, bit_depth);
396
          else
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            if (bit_depth <= 8)
              *pix_ptr++ = get_value (pnm_file, bit_depth);
            else
            {
              tmp16 = get_value (pnm_file, bit_depth);
              *pix_ptr = (png_byte) ((tmp16 >> 8) & 0xFF);
              pix_ptr++;
              *pix_ptr = (png_byte) (tmp16 & 0xFF);
              pix_ptr++;
            }
        }

        if (alpha) /* read alpha-channel from pgm file */
        {
          if (alpha_raw)
            *pix_ptr++ = get_data (alpha_file, alpha_depth);
413
          else
414 415 416 417 418 419 420 421 422 423
            if (alpha_depth <= 8)
              *pix_ptr++ = get_value (alpha_file, bit_depth);
            else
            {
              tmp16 = get_value (alpha_file, bit_depth);
              *pix_ptr++ = (png_byte) ((tmp16 >> 8) & 0xFF);
              *pix_ptr++ = (png_byte) (tmp16 & 0xFF);
            }
        } /* if alpha */
      } /* if packed_bitmap */
424 425 426 427
    } /* end for col */
  } /* end for row */

  /* prepare the standard PNG structures */
428 429
  png_ptr = png_create_write_struct (png_get_libpng_ver(NULL), NULL, NULL,
      NULL);
430 431 432 433 434 435 436 437 438 439 440
  if (!png_ptr)
  {
    return FALSE;
  }
  info_ptr = png_create_info_struct (png_ptr);
  if (!info_ptr)
  {
    png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
    return FALSE;
  }

441
#if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
442 443 444 445 446
  if (packed_bitmap == TRUE)
  {
    png_set_packing (png_ptr);
    png_set_invert_mono (png_ptr);
  }
447
#endif
448

449
  /* setjmp() must be called in every function that calls a PNG-reading libpng function */
450
  if (setjmp (png_jmpbuf(png_ptr)))
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  {
    png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
    return FALSE;
  }

  /* initialize the png structure */
  png_init_io (png_ptr, png_file);

  /* we're going to write more or less the same PNG as the input file */
  png_set_IHDR (png_ptr, info_ptr, width, height, bit_depth, color_type,
    (!interlace) ? PNG_INTERLACE_NONE : PNG_INTERLACE_ADAM7,
    PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  /* write the file header information */
  png_write_info (png_ptr, info_ptr);

  /* if needed we will allocate memory for an new array of row-pointers */
  if (row_pointers == (unsigned char**) NULL)
  {
470 471
    if ((row_pointers = (png_byte **)
        malloc (height * sizeof (png_bytep))) == NULL)
472 473 474 475 476 477 478
    {
      png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
      return FALSE;
    }
  }

  /* set the individual row_pointers to point at the correct offsets */
479
  for (i = 0; i < (int) height; i++)
480 481 482 483
    row_pointers[i] = png_pixels + i * row_bytes;

  /* write out the entire image data in one call */
  png_write_image (png_ptr, row_pointers);
484

485
  /* write the additional chunks to the PNG file (not really needed) */
486
  png_write_end (png_ptr, info_ptr);
487 488

  /* clean up after the write, and free any memory allocated */
489
  png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
490

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
  if (row_pointers != (unsigned char**) NULL)
    free (row_pointers);
  if (png_pixels != (unsigned char*) NULL)
    free (png_pixels);

  return TRUE;
} /* end of pnm2png */

/*
 * get_token() - gets the first string after whitespace
 */

void get_token(FILE *pnm_file, char *token)
{
  int i = 0;
506
  int ret;
507

508
  /* remove white-space and comment lines */
509 510
  do
  {
511 512 513 514 515 516 517 518 519 520 521
    ret = fgetc(pnm_file);
    if (ret == '#') {
      /* the rest of this line is a comment */
      do
      {
        ret = fgetc(pnm_file);
      }
      while ((ret != '\n') && (ret != '\r') && (ret != EOF));
    }
    if (ret == EOF) break;
    token[i] = (unsigned char) ret;
522 523 524 525 526 527
  }
  while ((token[i] == '\n') || (token[i] == '\r') || (token[i] == ' '));

  /* read string */
  do
  {
528 529
    ret = fgetc(pnm_file);
    if (ret == EOF) break;
530
    i++;
531
    token[i] = (unsigned char) ret;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
  }
  while ((token[i] != '\n') && (token[i] != '\r') && (token[i] != ' '));

  token[i] = '\0';

  return;
}

/*
 * get_data() - takes first byte and converts into next pixel value,
 *        taking as much bits as defined by bit-depth and
 *        using the bit-depth to fill up a byte (0Ah -> AAh)
 */

png_uint_32 get_data (FILE *pnm_file, int depth)
{
  static int bits_left = 0;
  static int old_value = 0;
  static int mask = 0;
  int i;
  png_uint_32 ret_value;

  if (mask == 0)
    for (i = 0; i < depth; i++)
      mask = (mask >> 1) | 0x80;

  if (bits_left <= 0)
  {
    old_value = fgetc (pnm_file);
    bits_left = 8;
  }

  ret_value = old_value & mask;
  for (i = 1; i < (8 / depth); i++)
    ret_value = ret_value || (ret_value >> depth);

  old_value = (old_value << depth) & 0xFF;
  bits_left -= depth;

  return ret_value;
}

/*
 * get_value() - takes first (numeric) string and converts into number,
 *         using the bit-depth to fill up a byte (0Ah -> AAh)
 */

png_uint_32 get_value (FILE *pnm_file, int depth)
{
  static png_uint_32 mask = 0;
  png_byte token[16];
583
  unsigned long ul_ret_value;
584 585 586 587 588 589 590
  png_uint_32 ret_value;
  int i = 0;

  if (mask == 0)
    for (i = 0; i < depth; i++)
      mask = (mask << 1) | 0x01;

591
  get_token (pnm_file, (char *) token);
592 593
  sscanf ((const char *) token, "%lu", &ul_ret_value);
  ret_value = (png_uint_32) ul_ret_value;
594 595 596 597 598 599 600 601 602 603 604 605

  ret_value &= mask;

  if (depth < 8)
    for (i = 0; i < (8 / depth); i++)
      ret_value = (ret_value << depth) || ret_value;

  return ret_value;
}

/* end of source */