write_bmp.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <grass/gis.h>
  5. #include "pngdriver.h"
  6. static unsigned char *put_2(unsigned char *p, unsigned int n)
  7. {
  8. *p++ = n & 0xFF;
  9. n >>= 8;
  10. *p++ = n & 0xFF;
  11. return p;
  12. }
  13. static unsigned char *put_4(unsigned char *p, unsigned int n)
  14. {
  15. *p++ = n & 0xFF;
  16. n >>= 8;
  17. *p++ = n & 0xFF;
  18. n >>= 8;
  19. *p++ = n & 0xFF;
  20. n >>= 8;
  21. *p++ = n & 0xFF;
  22. return p;
  23. }
  24. static void make_bmp_header(unsigned char *p)
  25. {
  26. *p++ = 'B';
  27. *p++ = 'M';
  28. p = put_4(p, HEADER_SIZE + png.width * png.height * 4);
  29. p = put_4(p, 0);
  30. p = put_4(p, HEADER_SIZE);
  31. p = put_4(p, 40);
  32. p = put_4(p, png.width);
  33. p = put_4(p, -png.height);
  34. p = put_2(p, 1);
  35. p = put_2(p, 32);
  36. p = put_4(p, 0);
  37. p = put_4(p, png.width * png.height * 4);
  38. p = put_4(p, 0);
  39. p = put_4(p, 0);
  40. p = put_4(p, 0);
  41. p = put_4(p, 0);
  42. }
  43. void write_bmp(void)
  44. {
  45. char header[HEADER_SIZE];
  46. FILE *output;
  47. int x, y;
  48. unsigned int *p;
  49. output = fopen(png.file_name, "wb");
  50. if (!output)
  51. G_fatal_error("PNG: couldn't open output file %s", png.file_name);
  52. memset(header, 0, sizeof(header));
  53. make_bmp_header(header);
  54. fwrite(header, sizeof(header), 1, output);
  55. for (y = 0, p = png.grid; y < png.height; y++) {
  56. for (x = 0; x < png.width; x++, p++) {
  57. unsigned int c = *p;
  58. int r, g, b, a;
  59. png_get_pixel(c, &r, &g, &b, &a);
  60. fputc((unsigned char)b, output);
  61. fputc((unsigned char)g, output);
  62. fputc((unsigned char)r, output);
  63. fputc((unsigned char)a, output);
  64. }
  65. }
  66. fclose(output);
  67. }