read_ppm.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*!
  2. \file lib/cairodriver/read_ppm.c
  3. \brief GRASS cairo display driver - read PPM image (lower level functions)
  4. (C) 2007-2008, 2011 by Lars Ahlzen and the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author Lars Ahlzen <lars ahlzen.com> (original contibutor)
  8. \author Glynn Clements
  9. */
  10. #include <grass/glocale.h>
  11. #include "cairodriver.h"
  12. void cairo_read_ppm(void)
  13. {
  14. char *mask_name = G_store(ca.file_name);
  15. FILE *input, *mask;
  16. int x, y;
  17. int i_width, i_height, maxval;
  18. input = fopen(ca.file_name, "rb");
  19. if (!input)
  20. G_fatal_error(_("Cairo: unable to open input file <%s>"),
  21. ca.file_name);
  22. if (fscanf(input, "P6 %d %d %d", &i_width, &i_height, &maxval) != 3)
  23. G_fatal_error(_("Cairo: invalid input file <%s>"),
  24. ca.file_name);
  25. fgetc(input);
  26. if (i_width != ca.width || i_height != ca.height)
  27. G_fatal_error(_("Cairo: input file has incorrect dimensions: "
  28. "expected: %dx%d got: %dx%d"),
  29. ca.width, ca.height, i_width, i_height);
  30. mask_name[strlen(mask_name) - 2] = 'g';
  31. mask = fopen(mask_name, "rb");
  32. if (!mask)
  33. G_fatal_error(_("Cairo: unable to open input mask file <%s>"),
  34. mask_name);
  35. if (fscanf(mask, "P5 %d %d %d", &i_width, &i_height, &maxval) != 3)
  36. G_fatal_error(_("Cairo: invalid input mask file <%s>"),
  37. mask_name);
  38. fgetc(mask);
  39. if (i_width != ca.width || i_height != ca.height)
  40. G_fatal_error(_("Cairo: input mask file has incorrect dimensions: "
  41. "expected: %dx%d got: %dx%d"),
  42. ca.width, ca.height, i_width, i_height);
  43. G_free(mask_name);
  44. for (y = 0; y < ca.height; y++) {
  45. unsigned int *row = (unsigned int *)(ca.grid + y * ca.stride);
  46. for (x = 0; x < ca.width; x++) {
  47. int r = fgetc(input);
  48. int g = fgetc(input);
  49. int b = fgetc(input);
  50. int a = fgetc(mask);
  51. r = r * 255 / maxval;
  52. g = g * 255 / maxval;
  53. b = b * 255 / maxval;
  54. a = a * 255 / maxval;
  55. if (a > 0 && a < 0xFF) {
  56. r = r * a / 0xFF;
  57. g = g * a / 0xFF;
  58. b = b * a / 0xFF;
  59. }
  60. row[x] = (a << 24) | (r << 16) | (g << 8) | (b << 0);
  61. }
  62. }
  63. fclose(input);
  64. fclose(mask);
  65. }