read_bmp.c 1.9 KB

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