read_ppm.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <grass/gis.h>
  5. #include "pngdriver.h"
  6. void read_ppm(void)
  7. {
  8. FILE *input;
  9. int x, y;
  10. int i_width, i_height, maxval;
  11. unsigned int rgb_mask = png_get_color(255, 255, 255, 0);
  12. unsigned int *p;
  13. if (!png.true_color)
  14. G_fatal_error("PNG: cannot use PPM/PGM with indexed color");
  15. input = fopen(png.file_name, "rb");
  16. if (!input)
  17. G_fatal_error("PNG: couldn't open input file %s", png.file_name);
  18. if (fscanf(input, "P6 %d %d %d", &i_width, &i_height, &maxval) != 3)
  19. G_fatal_error("PNG: invalid input file %s", png.file_name);
  20. fgetc(input);
  21. if (i_width != png.width || i_height != png.height)
  22. G_fatal_error
  23. ("PNG: input file has incorrect dimensions: expected: %dx%d got: %dx%d",
  24. png.width, png.height, i_width, i_height);
  25. for (y = 0, p = png.grid; y < png.height; y++) {
  26. for (x = 0; x < png.width; x++, p++) {
  27. unsigned int c = *p;
  28. int r = fgetc(input);
  29. int g = fgetc(input);
  30. int b = fgetc(input);
  31. r = r * 255 / maxval;
  32. g = g * 255 / maxval;
  33. b = b * 255 / maxval;
  34. c &= ~rgb_mask;
  35. c |= png_get_color(r, g, b, 0);
  36. *p = c;
  37. }
  38. }
  39. fclose(input);
  40. }
  41. void read_pgm(void)
  42. {
  43. char *mask_name = G_store(png.file_name);
  44. FILE *input;
  45. int x, y;
  46. int i_width, i_height, maxval;
  47. unsigned int rgb_mask = png_get_color(255, 255, 255, 0);
  48. unsigned int *p;
  49. if (!png.true_color)
  50. G_fatal_error("PNG: cannot use PPM/PGM with indexed color");
  51. mask_name[strlen(mask_name) - 2] = 'g';
  52. input = fopen(mask_name, "rb");
  53. if (!input)
  54. G_fatal_error("PNG: couldn't open input mask file %s", mask_name);
  55. if (fscanf(input, "P5 %d %d %d", &i_width, &i_height, &maxval) != 3)
  56. G_fatal_error("PNG: invalid input mask file %s", mask_name);
  57. fgetc(input);
  58. if (i_width != png.width || i_height != png.height)
  59. G_fatal_error
  60. ("PNG: input mask file has incorrect dimensions: expected: %dx%d got: %dx%d",
  61. png.width, png.height, i_width, i_height);
  62. G_free(mask_name);
  63. for (y = 0, p = png.grid; y < png.height; y++) {
  64. for (x = 0; x < png.width; x++, p++) {
  65. unsigned int c = *p;
  66. int k = fgetc(input);
  67. k = k * 255 / maxval;
  68. c &= rgb_mask;
  69. c |= png_get_color(0, 0, 0, 255 - k);
  70. *p = c;
  71. }
  72. }
  73. fclose(input);
  74. }