read_bmp.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*!
  2. \file lib/pngdriver/read_bmp.c
  3. \brief GRASS png display driver - read bitmap (lower level functions)
  4. (C) 2007-2014 by Glynn Clements 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 Glynn Clements
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <grass/gis.h>
  13. #include "pngdriver.h"
  14. static unsigned int get_2(const unsigned char **q)
  15. {
  16. const unsigned char *p = *q;
  17. unsigned int n = (p[0] << 0) | (p[1] << 8);
  18. *q += 2;
  19. return n;
  20. }
  21. static unsigned int get_4(const unsigned char **q)
  22. {
  23. const unsigned char *p = *q;
  24. unsigned int n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
  25. *q += 4;
  26. return n;
  27. }
  28. static int read_bmp_header(const unsigned char *p)
  29. {
  30. if (*p++ != 'B')
  31. return 0;
  32. if (*p++ != 'M')
  33. return 0;
  34. if (get_4(&p) != HEADER_SIZE + png.width * png.height * 4)
  35. return 0;
  36. get_4(&p);
  37. if (get_4(&p) != HEADER_SIZE)
  38. return 0;
  39. if (get_4(&p) != 40)
  40. return 0;
  41. if (get_4(&p) != png.width)
  42. return 0;
  43. if (get_4(&p) != -png.height)
  44. return 0;
  45. get_2(&p);
  46. if (get_2(&p) != 32)
  47. return 0;
  48. if (get_4(&p) != 0)
  49. return 0;
  50. if (get_4(&p) != png.width * png.height * 4)
  51. return 0;
  52. get_4(&p);
  53. get_4(&p);
  54. get_4(&p);
  55. get_4(&p);
  56. return 1;
  57. }
  58. void read_bmp(void)
  59. {
  60. char header[HEADER_SIZE];
  61. FILE *input;
  62. int x, y;
  63. unsigned int *p;
  64. if (!png.true_color)
  65. G_fatal_error("PNG: cannot use BMP with indexed color");
  66. input = fopen(png.file_name, "rb");
  67. if (!input)
  68. G_fatal_error("PNG: couldn't open input file %s", png.file_name);
  69. if (fread(header, sizeof(header), 1, input) != 1)
  70. G_fatal_error("PNG: invalid input file %s", png.file_name);
  71. if (!read_bmp_header(header))
  72. G_fatal_error("PNG: invalid BMP header for %s", png.file_name);
  73. for (y = 0, p = png.grid; y < png.height; y++) {
  74. for (x = 0; x < png.width; x++, p++) {
  75. int b = fgetc(input);
  76. int g = fgetc(input);
  77. int r = fgetc(input);
  78. int a = fgetc(input);
  79. unsigned int c = png_get_color(r, g, b, a);
  80. *p = c;
  81. }
  82. }
  83. fclose(input);
  84. }