write_bmp.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. \file lib/pngdriver/write_bmp.c
  3. \brief GRASS png display driver - write 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 char *put_2(unsigned char *p, unsigned int n)
  15. {
  16. *p++ = n & 0xFF;
  17. n >>= 8;
  18. *p++ = n & 0xFF;
  19. return p;
  20. }
  21. static unsigned char *put_4(unsigned char *p, unsigned int n)
  22. {
  23. *p++ = n & 0xFF;
  24. n >>= 8;
  25. *p++ = n & 0xFF;
  26. n >>= 8;
  27. *p++ = n & 0xFF;
  28. n >>= 8;
  29. *p++ = n & 0xFF;
  30. return p;
  31. }
  32. static void make_bmp_header(unsigned char *p)
  33. {
  34. *p++ = 'B';
  35. *p++ = 'M';
  36. p = put_4(p, HEADER_SIZE + png.width * png.height * 4);
  37. p = put_4(p, 0);
  38. p = put_4(p, HEADER_SIZE);
  39. p = put_4(p, 40);
  40. p = put_4(p, png.width);
  41. p = put_4(p, -png.height);
  42. p = put_2(p, 1);
  43. p = put_2(p, 32);
  44. p = put_4(p, 0);
  45. p = put_4(p, png.width * png.height * 4);
  46. p = put_4(p, 0);
  47. p = put_4(p, 0);
  48. p = put_4(p, 0);
  49. p = put_4(p, 0);
  50. }
  51. void write_bmp(void)
  52. {
  53. unsigned char header[HEADER_SIZE];
  54. FILE *output;
  55. int x, y;
  56. unsigned int *p;
  57. output = fopen(png.file_name, "wb");
  58. if (!output)
  59. G_fatal_error("PNG: couldn't open output file %s", png.file_name);
  60. memset(header, 0, sizeof(header));
  61. make_bmp_header(header);
  62. fwrite(header, sizeof(header), 1, output);
  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 r, g, b, a;
  67. png_get_pixel(c, &r, &g, &b, &a);
  68. fputc((unsigned char)b, output);
  69. fputc((unsigned char)g, output);
  70. fputc((unsigned char)r, output);
  71. fputc((unsigned char)a, output);
  72. }
  73. }
  74. fclose(output);
  75. }