read_bmp.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*!
  2. \file lib/cairodriver/read_bmp.c
  3. \brief GRASS cairo display driver - read bitmap (lower level functions)
  4. (C) 2007-2008 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 <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <grass/gis.h>
  14. #include <grass/glocale.h>
  15. #include "cairodriver.h"
  16. static unsigned int get_2(const unsigned char **q)
  17. {
  18. const unsigned char *p = *q;
  19. unsigned int n = (p[0] << 0) | (p[1] << 8);
  20. *q += 2;
  21. return n;
  22. }
  23. static unsigned int get_4(const unsigned char **q)
  24. {
  25. const unsigned char *p = *q;
  26. unsigned int n = (p[0] << 0) | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
  27. *q += 4;
  28. return n;
  29. }
  30. static int read_bmp_header(const unsigned char *p)
  31. {
  32. if (*p++ != 'B')
  33. return 0;
  34. if (*p++ != 'M')
  35. return 0;
  36. if (get_4(&p) != HEADER_SIZE + ca.width * ca.height * 4)
  37. return 0;
  38. get_4(&p);
  39. if (get_4(&p) != HEADER_SIZE)
  40. return 0;
  41. if (get_4(&p) != 40)
  42. return 0;
  43. if (get_4(&p) != ca.width)
  44. return 0;
  45. if (get_4(&p) != -ca.height)
  46. return 0;
  47. get_2(&p);
  48. if (get_2(&p) != 32)
  49. return 0;
  50. if (get_4(&p) != 0)
  51. return 0;
  52. if (get_4(&p) != ca.width * ca.height * 4)
  53. return 0;
  54. get_4(&p);
  55. get_4(&p);
  56. get_4(&p);
  57. get_4(&p);
  58. return 1;
  59. }
  60. void cairo_read_bmp(void)
  61. {
  62. char header[HEADER_SIZE];
  63. FILE *input;
  64. input = fopen(ca.file_name, "rb");
  65. if (!input)
  66. G_fatal_error(_("Cairo: unable to open input file <%s>"),
  67. ca.file_name);
  68. if (fread(header, sizeof(header), 1, input) != 1)
  69. G_fatal_error(_("Cairo: invalid input file <%s>"),
  70. ca.file_name);
  71. if (!read_bmp_header(header))
  72. G_fatal_error(_("Cairo: Invalid BMP header for <%s>"),
  73. ca.file_name);
  74. fread(ca.grid, ca.stride, ca.height, input);
  75. fclose(input);
  76. }