GRASS GIS 7 Programmer's Manual  7.9.dev(2021)-e5379bbd7
pngdriver/write_bmp.c
Go to the documentation of this file.
1 /*!
2  \file lib/pngdriver/write_bmp.c
3 
4  \brief GRASS png display driver - write bitmap (lower level functions)
5 
6  (C) 2007-2014 by Glynn Clements and the GRASS Development Team
7 
8  This program is free software under the GNU General Public License
9  (>=v2). Read the file COPYING that comes with GRASS for details.
10 
11  \author Glynn Clements
12 */
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 
18 #include <grass/gis.h>
19 #include "pngdriver.h"
20 
21 static unsigned char *put_2(unsigned char *p, unsigned int n)
22 {
23  *p++ = n & 0xFF;
24  n >>= 8;
25  *p++ = n & 0xFF;
26  return p;
27 }
28 
29 static unsigned char *put_4(unsigned char *p, unsigned int n)
30 {
31  *p++ = n & 0xFF;
32  n >>= 8;
33  *p++ = n & 0xFF;
34  n >>= 8;
35  *p++ = n & 0xFF;
36  n >>= 8;
37  *p++ = n & 0xFF;
38  return p;
39 }
40 
41 static void make_bmp_header(unsigned char *p)
42 {
43  *p++ = 'B';
44  *p++ = 'M';
45 
46  p = put_4(p, HEADER_SIZE + png.width * png.height * 4);
47  p = put_4(p, 0);
48  p = put_4(p, HEADER_SIZE);
49 
50  p = put_4(p, 40);
51  p = put_4(p, png.width);
52  p = put_4(p, -png.height);
53  p = put_2(p, 1);
54  p = put_2(p, 32);
55  p = put_4(p, 0);
56  p = put_4(p, png.width * png.height * 4);
57  p = put_4(p, 0);
58  p = put_4(p, 0);
59  p = put_4(p, 0);
60  p = put_4(p, 0);
61 }
62 
63 void write_bmp(void)
64 {
65  unsigned char header[HEADER_SIZE];
66  FILE *output;
67  int x, y;
68  unsigned int *p;
69 
70  output = fopen(png.file_name, "wb");
71  if (!output)
72  G_fatal_error("PNG: couldn't open output file %s", png.file_name);
73 
74  memset(header, 0, sizeof(header));
75  make_bmp_header(header);
76  fwrite(header, sizeof(header), 1, output);
77 
78  for (y = 0, p = png.grid; y < png.height; y++) {
79  for (x = 0; x < png.width; x++, p++) {
80  unsigned int c = *p;
81  int r, g, b, a;
82 
83  png_get_pixel(c, &r, &g, &b, &a);
84 
85  fputc((unsigned char)b, output);
86  fputc((unsigned char)g, output);
87  fputc((unsigned char)r, output);
88  fputc((unsigned char)a, output);
89  }
90  }
91 
92  fclose(output);
93 }
void void void void G_fatal_error(const char *,...) __attribute__((format(printf
#define HEADER_SIZE
Definition: cairodriver.h:45
int width
Definition: pngdriver.h:43
GRASS png display driver - header file.
int height
Definition: pngdriver.h:43
void png_get_pixel(unsigned int pixel, int *r, int *g, int *b, int *a)
Definition: color_table.c:112
#define x
struct png_state png
double b
Definition: r_raster.c:39
char * file_name
Definition: pngdriver.h:33
unsigned int * grid
Definition: pngdriver.h:44
float g
Definition: named_colr.c:8
void output(const char *fmt,...)
void write_bmp(void)
double r
Definition: r_raster.c:39