The R Project SVN R

Rev

Rev 55709 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 55709 Rev 59039
1
/*
1
/*
2
 *  R : A Computer Language for Statistical Data Analysis
2
 *  R : A Computer Language for Statistical Data Analysis
3
 *  Copyright (C) 1999-2011  Guido Masarotto and the R Development Core Team
3
 *  Copyright (C) 1999-2011  Guido Masarotto and the R Core Team
4
 *
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
8
 *  (at your option) any later version.
9
 *
9
 *
10
 *  This program is distributed in the hope that it will be useful,
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
13
 *  GNU General Public License for more details.
14
 *
14
 *
15
 *  You should have received a copy of the GNU General Public License
15
 *  You should have received a copy of the GNU General Public License
16
 *  along with this program; if not, a copy is available at
16
 *  along with this program; if not, a copy is available at
17
 *  http://www.r-project.org/Licenses/
17
 *  http://www.r-project.org/Licenses/
18
 */
18
 */
19
 
19
 
20
 
20
 
21
/*
21
/*
22
 * This file aims to be system independent so it sees the underlying
22
 * This file aims to be system independent so it sees the underlying
23
 * structures only using:
23
 * structures only using:
24
 * void *d : an 'opaque' view of the source of the pixels;
24
 * void *d : an 'opaque' view of the source of the pixels;
25
 * int width, height: dimensions in pixels;
25
 * int width, height: dimensions in pixels;
26
 * unsigned int (*gp)(void *d, int x, int y): a function which
26
 * unsigned int (*gp)(void *d, int x, int y): a function which
27
 *     returns the colour of the (x,y) pixels stored either as
27
 *     returns the colour of the (x,y) pixels stored either as
28
 *     BGR (R model, see GraphicsDevice.h) or as RGB in the
28
 *     BGR (R model, see GraphicsDevice.h) or as RGB in the
29
 *     24 least sig. bits (8 bit for channel).
29
 *     24 least sig. bits (8 bit for channel).
30
 *     (0,0) is the left-top corner. (3,2) is the third pixel
30
 *     (0,0) is the left-top corner. (3,2) is the third pixel
31
 *     in the fourth scanline.
31
 *     in the fourth scanline.
32
 * int bgr: if != 0, order is BGR else is RGB.
32
 * int bgr: if != 0, order is BGR else is RGB.
33
 * int quality: only for jpeg (0-100 measure of how much to compress).
33
 * int quality: only for jpeg (0-100 measure of how much to compress).
34
 * FILE * fp is the destination.
34
 * FILE * fp is the destination.
35
 *
35
 *
36
 */
36
 */
37
 
37
 
38
#include <stdio.h>
38
#include <stdio.h>
39
#include <stdlib.h>
39
#include <stdlib.h>
40
#include <setjmp.h>
40
#include <setjmp.h>
41
 
41
 
42
/* 8 bits red, green and blue channel */
42
/* 8 bits red, green and blue channel */
43
#define DECLARESHIFTS int RSHIFT=(bgr)?0:16, GSHIFT=8, BSHIFT=(bgr)?16:0
43
#define DECLARESHIFTS int RSHIFT=(bgr)?0:16, GSHIFT=8, BSHIFT=(bgr)?16:0
44
#define GETRED(col)    (((col) >> RSHIFT) & 0xFF)
44
#define GETRED(col)    (((col) >> RSHIFT) & 0xFF)
45
#define GETGREEN(col)  (((col) >> GSHIFT) & 0xFF)
45
#define GETGREEN(col)  (((col) >> GSHIFT) & 0xFF)
46
#define GETBLUE(col)   (((col) >> BSHIFT) & 0xFF)
46
#define GETBLUE(col)   (((col) >> BSHIFT) & 0xFF)
47
#define GETALPHA(col)   (((col) >> 24) & 0xFF)
47
#define GETALPHA(col)   (((col) >> 24) & 0xFF)
48
 
48
 
49
#include <R_ext/Error.h>
49
#include <R_ext/Error.h>
50
 
50
 
51
#ifdef HAVE_PNG
51
#ifdef HAVE_PNG
52
 
52
 
53
#include "png.h"
53
#include "png.h"
54
/*
54
/*
55
 * Try to save the content of the device 'd' in 'filename' as png.
55
 * Try to save the content of the device 'd' in 'filename' as png.
56
 * If numbers of colors is less than 256 we use a 'palette' png.
56
 * If numbers of colors is less than 256 we use a 'palette' png.
57
 * Return 1 on success, 0 on failure
57
 * Return 1 on success, 0 on failure
58
*/
58
*/
59
 
59
 
60
/*
60
/*
61
    I don't use 'error' since (1) we must free 'scanline' and
61
    I don't use 'error' since (1) we must free 'scanline' and
62
   (2) we can be arrived here from a button or menuitem callback maybe
62
   (2) we can be arrived here from a button or menuitem callback maybe
63
   in a different thread from the one where R runs.
63
   in a different thread from the one where R runs.
64
*/
64
*/
65
static void my_png_error(png_structp png_ptr, png_const_charp msg)
65
static void my_png_error(png_structp png_ptr, png_const_charp msg)
66
{
66
{
67
    R_ShowMessage((char *) msg);
67
    R_ShowMessage((char *) msg);
68
#if PNG_LIBPNG_VER < 10400
68
#if PNG_LIBPNG_VER < 10400
69
    longjmp(png_ptr->jmpbuf,1);
69
    longjmp(png_ptr->jmpbuf,1);
70
#else
70
#else
71
    longjmp(png_jmpbuf(png_ptr),1);
71
    longjmp(png_jmpbuf(png_ptr),1);
72
#endif
72
#endif
73
}
73
}
74
 
74
 
75
static void my_png_warning(png_structp png_ptr, png_const_charp msg)
75
static void my_png_warning(png_structp png_ptr, png_const_charp msg)
76
{
76
{
77
    warning("libpng: %s",(char *) msg);
77
    warning("libpng: %s",(char *) msg);
78
}
78
}
79
 
79
 
80
__declspec(dllexport)
80
__declspec(dllexport)
81
int R_SaveAsPng(void  *d, int width, int height,
81
int R_SaveAsPng(void  *d, int width, int height,
82
		unsigned int (*gp)(void *, int, int),
82
		unsigned int (*gp)(void *, int, int),
83
		int bgr, FILE *fp, unsigned int transparent, int res)
83
		int bgr, FILE *fp, unsigned int transparent, int res)
84
{
84
{
85
    png_structp png_ptr;
85
    png_structp png_ptr;
86
    png_infop info_ptr;
86
    png_infop info_ptr;
87
    unsigned int  col, palette[256];
87
    unsigned int  col, palette[256];
88
    png_color pngpalette[256];
88
    png_color pngpalette[256];
89
    png_bytep pscanline;
89
    png_bytep pscanline;
90
    png_bytep scanline = (png_bytep) calloc((size_t)(4*width),sizeof(png_byte));
90
    png_bytep scanline = (png_bytep) calloc((size_t)(4*width),sizeof(png_byte));
91
    png_byte trans[256];
91
    png_byte trans[256];
92
    png_color_16 trans_values[1];
92
    png_color_16 trans_values[1];
93
    int i, j, r, ncols, mid, high, low, withpalette, have_alpha;
93
    int i, j, r, ncols, mid, high, low, withpalette, have_alpha;
94
    volatile DECLARESHIFTS;
94
    volatile DECLARESHIFTS;
95
 
95
 
96
    /* Have we enough memory?*/
96
    /* Have we enough memory?*/
97
    if (scanline == NULL)
97
    if (scanline == NULL)
98
	return 0;
98
	return 0;
99
 
99
 
100
    if (fp == NULL) {
100
    if (fp == NULL) {
101
	free(scanline);
101
	free(scanline);
102
	return 0;
102
	return 0;
103
    }
103
    }
104
 
104
 
105
    /* Create and initialize the png_struct with the desired error handler
105
    /* Create and initialize the png_struct with the desired error handler
106
     * functions.  If you want to use the default stderr and longjump method,
106
     * functions.  If you want to use the default stderr and longjump method,
107
     * you can supply NULL for the last three parameters.  We also check that
107
     * you can supply NULL for the last three parameters.  We also check that
108
     * the library version is compatible with the one used at compile time,
108
     * the library version is compatible with the one used at compile time,
109
     * in case we are using dynamically linked libraries.  REQUIRED.
109
     * in case we are using dynamically linked libraries.  REQUIRED.
110
     */
110
     */
111
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
111
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
112
    if (png_ptr == NULL) {
112
    if (png_ptr == NULL) {
113
	free(scanline);
113
	free(scanline);
114
	return 0;
114
	return 0;
115
    }
115
    }
116
 
116
 
117
    /* Allocate/initialize the image information data.  REQUIRED */
117
    /* Allocate/initialize the image information data.  REQUIRED */
118
    info_ptr = png_create_info_struct(png_ptr);
118
    info_ptr = png_create_info_struct(png_ptr);
119
    if (info_ptr == NULL) {
119
    if (info_ptr == NULL) {
120
	free(scanline);
120
	free(scanline);
121
	png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
121
	png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
122
	return 0;
122
	return 0;
123
    }
123
    }
124
 
124
 
125
    /* Set error handling.  REQUIRED if you aren't supplying your own
125
    /* Set error handling.  REQUIRED if you aren't supplying your own
126
     * error handling functions in the png_create_write_struct() call.
126
     * error handling functions in the png_create_write_struct() call.
127
     */
127
     */
128
#if PNG_LIBPNG_VER < 10400
128
#if PNG_LIBPNG_VER < 10400
129
    if (setjmp(png_ptr->jmpbuf))
129
    if (setjmp(png_ptr->jmpbuf))
130
#else
130
#else
131
    if (setjmp(png_jmpbuf(png_ptr)))
131
    if (setjmp(png_jmpbuf(png_ptr)))
132
#endif
132
#endif
133
{
133
{
134
	/* If we get here, we had a problem writing the file */
134
	/* If we get here, we had a problem writing the file */
135
	free(scanline);
135
	free(scanline);
136
	png_destroy_write_struct(&png_ptr, &info_ptr);
136
	png_destroy_write_struct(&png_ptr, &info_ptr);
137
	return 0;
137
	return 0;
138
    }
138
    }
139
    png_set_error_fn(png_ptr, NULL, my_png_error, my_png_warning);
139
    png_set_error_fn(png_ptr, NULL, my_png_error, my_png_warning);
140
 
140
 
141
    /* I/O initialization functions is REQUIRED */
141
    /* I/O initialization functions is REQUIRED */
142
    png_init_io(png_ptr, fp);
142
    png_init_io(png_ptr, fp);
143
    /* Have we less than 256 different colors? */
143
    /* Have we less than 256 different colors? */
144
    ncols = 0;
144
    ncols = 0;
145
    if(transparent) palette[ncols++] = transparent & 0xFFFFFF;
145
    if(transparent) palette[ncols++] = transparent & 0xFFFFFF;
146
    mid = ncols;
146
    mid = ncols;
147
    withpalette = 1;
147
    withpalette = 1;
148
    have_alpha = 0;
148
    have_alpha = 0;
149
    for (i = 0; (i < height) && withpalette ; i++) {
149
    for (i = 0; (i < height) && withpalette ; i++) {
150
	for (j = 0; (j < width) && withpalette ; j++) {
150
	for (j = 0; (j < width) && withpalette ; j++) {
151
	    col = gp(d,i,j);
151
	    col = gp(d,i,j);
152
	    if (GETALPHA(col) < 255) have_alpha = 1;
152
	    if (GETALPHA(col) < 255) have_alpha = 1;
153
	    /* binary search the palette: */
153
	    /* binary search the palette: */
154
	    low = 0;
154
	    low = 0;
155
	    high = ncols - 1;
155
	    high = ncols - 1;
156
	    while (low <= high) {
156
	    while (low <= high) {
157
		mid = (low + high)/2;
157
		mid = (low + high)/2;
158
		if ( col < palette[mid] ) high = mid - 1;
158
		if ( col < palette[mid] ) high = mid - 1;
159
		else if ( col > palette[mid] ) low  = mid + 1;
159
		else if ( col > palette[mid] ) low  = mid + 1;
160
		else break;
160
		else break;
161
	    }
161
	    }
162
	    if (high < low) {
162
	    if (high < low) {
163
		/* didn't find colour in palette, insert it: */
163
		/* didn't find colour in palette, insert it: */
164
		if (ncols >= 256) {
164
		if (ncols >= 256) {
165
		    withpalette = 0;
165
		    withpalette = 0;
166
		} else {
166
		} else {
167
		    for (r = ncols; r > low; r--)
167
		    for (r = ncols; r > low; r--)
168
			palette[r] = palette[r-1] ;
168
			palette[r] = palette[r-1] ;
169
		    palette[low] = col;
169
		    palette[low] = col;
170
		    ncols ++;
170
		    ncols ++;
171
		}
171
		}
172
	    }
172
	    }
173
	}
173
	}
174
    }
174
    }
175
    col = gp(d,0,0);
175
    col = gp(d,0,0);
176
    //have_alpha &= (transparent == 0);
176
    //have_alpha &= (transparent == 0);
177
 
177
 
178
    /* Set the image information here.  Width and height are up to 2^31,
178
    /* Set the image information here.  Width and height are up to 2^31,
179
     * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
179
     * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
180
     * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
180
     * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
181
     * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
181
     * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
182
     * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
182
     * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
183
     * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
183
     * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
184
     * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
184
     * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
185
     */
185
     */
186
    png_set_IHDR(png_ptr, info_ptr, width, height, 8,
186
    png_set_IHDR(png_ptr, info_ptr, width, height, 8,
187
		 withpalette ? PNG_COLOR_TYPE_PALETTE :
187
		 withpalette ? PNG_COLOR_TYPE_PALETTE :
188
		 (have_alpha ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB),
188
		 (have_alpha ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB),
189
		 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
189
		 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
190
		 PNG_FILTER_TYPE_BASE);
190
		 PNG_FILTER_TYPE_BASE);
191
 
191
 
192
    if (withpalette) {
192
    if (withpalette) {
193
	for (i = 0; i < ncols ; i++) {
193
	for (i = 0; i < ncols ; i++) {
194
	    col = palette[i];
194
	    col = palette[i];
195
	    if(transparent) {
195
	    if(transparent) {
196
		trans[i] = (col == transparent) ? 0:255;
196
		trans[i] = (col == transparent) ? 0:255;
197
		pngpalette[i].red = GETRED(col);
197
		pngpalette[i].red = GETRED(col);
198
		pngpalette[i].green = GETGREEN(col);
198
		pngpalette[i].green = GETGREEN(col);
199
		pngpalette[i].blue = GETBLUE(col);
199
		pngpalette[i].blue = GETBLUE(col);
200
	    } else {
200
	    } else {
201
		/* PNG needs NON-premultiplied alpha */
201
		/* PNG needs NON-premultiplied alpha */
202
		int a = GETALPHA(col);
202
		int a = GETALPHA(col);
203
		trans[i] = a;
203
		trans[i] = a;
204
		if(a == 255 || a == 0) {
204
		if(a == 255 || a == 0) {
205
		    pngpalette[i].red = GETRED(col);
205
		    pngpalette[i].red = GETRED(col);
206
		    pngpalette[i].green = GETGREEN(col);
206
		    pngpalette[i].green = GETGREEN(col);
207
		    pngpalette[i].blue = GETBLUE(col);
207
		    pngpalette[i].blue = GETBLUE(col);
208
		} else {
208
		} else {
209
		    pngpalette[i].red = 0.49 + 255.0*GETRED(col)/a;
209
		    pngpalette[i].red = 0.49 + 255.0*GETRED(col)/a;
210
		    pngpalette[i].green = 0.49 + 255.0*GETGREEN(col)/a;
210
		    pngpalette[i].green = 0.49 + 255.0*GETGREEN(col)/a;
211
		    pngpalette[i].blue = 0.49 + 255.0*GETBLUE(col)/a;
211
		    pngpalette[i].blue = 0.49 + 255.0*GETBLUE(col)/a;
212
 
212
 
213
		}
213
		}
214
	    }
214
	    }
215
	}
215
	}
216
	png_set_PLTE(png_ptr, info_ptr, pngpalette, ncols);
216
	png_set_PLTE(png_ptr, info_ptr, pngpalette, ncols);
217
	if (transparent || have_alpha)
217
	if (transparent || have_alpha)
218
	    png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
218
	    png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
219
    }
219
    }
220
    /* Deal with transparency */
220
    /* Deal with transparency */
221
    if(transparent && !withpalette) {
221
    if(transparent && !withpalette) {
222
	trans_values[0].red = GETRED(transparent);
222
	trans_values[0].red = GETRED(transparent);
223
	trans_values[0].blue = GETBLUE(transparent);
223
	trans_values[0].blue = GETBLUE(transparent);
224
	trans_values[0].green = GETGREEN(transparent);
224
	trans_values[0].green = GETGREEN(transparent);
225
	png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
225
	png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
226
    }
226
    }
227
 
227
 
228
    if(res > 0)
228
    if(res > 0)
229
	png_set_pHYs(png_ptr, info_ptr, res/0.0254, res/0.0254,
229
	png_set_pHYs(png_ptr, info_ptr, res/0.0254, res/0.0254,
230
		     PNG_RESOLUTION_METER);
230
		     PNG_RESOLUTION_METER);
231
 
231
 
232
    /* Write the file header information.  REQUIRED */
232
    /* Write the file header information.  REQUIRED */
233
    png_write_info(png_ptr, info_ptr);
233
    png_write_info(png_ptr, info_ptr);
234
 
234
 
235
    /*
235
    /*
236
     * Now, write the pixels
236
     * Now, write the pixels
237
     */
237
     */
238
    for (i = 0 ; i < height ; i++) {
238
    for (i = 0 ; i < height ; i++) {
239
	/* Build the scanline */
239
	/* Build the scanline */
240
	pscanline = scanline;
240
	pscanline = scanline;
241
	for (j = 0 ; j < width ; j++) {
241
	for (j = 0 ; j < width ; j++) {
242
	    col = gp(d, i, j);
242
	    col = gp(d, i, j);
243
	    if (withpalette) {
243
	    if (withpalette) {
244
		/* binary search the palette (the colour must be there): */
244
		/* binary search the palette (the colour must be there): */
245
		low = 0;  high = ncols - 1;
245
		low = 0;  high = ncols - 1;
246
		while (low <= high) {
246
		while (low <= high) {
247
		    mid = (low + high)/2;
247
		    mid = (low + high)/2;
248
		    if      (col < palette[mid]) high = mid - 1;
248
		    if      (col < palette[mid]) high = mid - 1;
249
		    else if (col > palette[mid]) low  = mid + 1;
249
		    else if (col > palette[mid]) low  = mid + 1;
250
		    else break;
250
		    else break;
251
		}
251
		}
252
		*pscanline++ = mid;
252
		*pscanline++ = mid;
253
	    } else {
253
	    } else {
254
		if(have_alpha) {
254
		if(have_alpha) {
255
		    /* PNG needs NON-premultiplied alpha */
255
		    /* PNG needs NON-premultiplied alpha */
256
		    int a = GETALPHA(col);
256
		    int a = GETALPHA(col);
257
		    if(a == 255 || a == 0) {
257
		    if(a == 255 || a == 0) {
258
			*pscanline++ = GETRED(col) ;
258
			*pscanline++ = GETRED(col) ;
259
			*pscanline++ = GETGREEN(col) ;
259
			*pscanline++ = GETGREEN(col) ;
260
			*pscanline++ = GETBLUE(col) ;
260
			*pscanline++ = GETBLUE(col) ;
261
			*pscanline++ =  a;
261
			*pscanline++ =  a;
262
		    } else {
262
		    } else {
263
			*pscanline++ = 0.49 + 255.0*GETRED(col)/a ;
263
			*pscanline++ = 0.49 + 255.0*GETRED(col)/a ;
264
			*pscanline++ = 0.49 + 255.0*GETGREEN(col)/a ;
264
			*pscanline++ = 0.49 + 255.0*GETGREEN(col)/a ;
265
			*pscanline++ = 0.49 + 255.0*GETBLUE(col)/a ;
265
			*pscanline++ = 0.49 + 255.0*GETBLUE(col)/a ;
266
			*pscanline++ =  a;
266
			*pscanline++ =  a;
267
		    }
267
		    }
268
		} else {
268
		} else {
269
		    *pscanline++ = GETRED(col) ;
269
		    *pscanline++ = GETRED(col) ;
270
		    *pscanline++ = GETGREEN(col) ;
270
		    *pscanline++ = GETGREEN(col) ;
271
		    *pscanline++ = GETBLUE(col) ;
271
		    *pscanline++ = GETBLUE(col) ;
272
		}
272
		}
273
	    }
273
	    }
274
	}
274
	}
275
	png_write_row(png_ptr, scanline);
275
	png_write_row(png_ptr, scanline);
276
    }
276
    }
277
 
277
 
278
    /* It is REQUIRED to call this to finish writing the rest of the file */
278
    /* It is REQUIRED to call this to finish writing the rest of the file */
279
    png_write_end(png_ptr, info_ptr);
279
    png_write_end(png_ptr, info_ptr);
280
 
280
 
281
    /* clean up after the write, and free any memory allocated */
281
    /* clean up after the write, and free any memory allocated */
282
    free(scanline);
282
    free(scanline);
283
    png_destroy_write_struct(&png_ptr, &info_ptr);
283
    png_destroy_write_struct(&png_ptr, &info_ptr);
284
 
284
 
285
    /* that's it */
285
    /* that's it */
286
    return 1;
286
    return 1;
287
}
287
}
288
 
288
 
289
#endif /* HAVE_PNG */
289
#endif /* HAVE_PNG */
290
 
290
 
291
 
291
 
292
#ifdef HAVE_JPEG
292
#ifdef HAVE_JPEG
293
 
293
 
294
/* jconfig.h included by jpeglib.h may define these unconditionally */
294
/* jconfig.h included by jpeglib.h may define these unconditionally */
295
#undef HAVE_STDDEF_H
295
#undef HAVE_STDDEF_H
296
#undef HAVE_STDLIB_H
296
#undef HAVE_STDLIB_H
297
#include <jpeglib.h>
297
#include <jpeglib.h>
298
 
298
 
299
/* Here's the extended error handler struct */
299
/* Here's the extended error handler struct */
300
 
300
 
301
struct my_error_mgr {
301
struct my_error_mgr {
302
    struct jpeg_error_mgr pub;	/* "public" fields */
302
    struct jpeg_error_mgr pub;	/* "public" fields */
303
    jmp_buf setjmp_buffer;	/* for return to caller */
303
    jmp_buf setjmp_buffer;	/* for return to caller */
304
};
304
};
305
 
305
 
306
typedef struct my_error_mgr * my_error_ptr;
306
typedef struct my_error_mgr * my_error_ptr;
307
 
307
 
308
/*
308
/*
309
 * Here's the routine that will replace the standard error_exit method:
309
 * Here's the routine that will replace the standard error_exit method:
310
*/
310
*/
311
 
311
 
312
static void my_error_exit (j_common_ptr cinfo)
312
static void my_error_exit (j_common_ptr cinfo)
313
{
313
{
314
    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
314
    /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
315
    my_error_ptr myerr = (my_error_ptr) cinfo->err;
315
    my_error_ptr myerr = (my_error_ptr) cinfo->err;
316
 
316
 
317
    /* Always display the message. */
317
    /* Always display the message. */
318
    (*cinfo->err->output_message) (cinfo);
318
    (*cinfo->err->output_message) (cinfo);
319
 
319
 
320
    /* Return control to the setjmp point */
320
    /* Return control to the setjmp point */
321
    longjmp(myerr->setjmp_buffer, 1);
321
    longjmp(myerr->setjmp_buffer, 1);
322
}
322
}
323
 
323
 
324
/* We also replace the output method */
324
/* We also replace the output method */
325
static void my_output_message (j_common_ptr cinfo)
325
static void my_output_message (j_common_ptr cinfo)
326
{
326
{
327
    char buffer[JMSG_LENGTH_MAX];
327
    char buffer[JMSG_LENGTH_MAX];
328
 
328
 
329
    /* Create the message */
329
    /* Create the message */
330
    (*cinfo->err->format_message) (cinfo, buffer);
330
    (*cinfo->err->format_message) (cinfo, buffer);
331
 
331
 
332
    /* and show it */
332
    /* and show it */
333
    R_ShowMessage(buffer);
333
    R_ShowMessage(buffer);
334
}
334
}
335
 
335
 
336
 
336
 
337
 
337
 
338
__declspec(dllexport)
338
__declspec(dllexport)
339
int R_SaveAsJpeg(void  *d, int width, int height,
339
int R_SaveAsJpeg(void  *d, int width, int height,
340
		unsigned int (*gp)(void *, int, int),
340
		unsigned int (*gp)(void *, int, int),
341
		int bgr, int quality, FILE *outfile, int res)
341
		int bgr, int quality, FILE *outfile, int res)
342
{
342
{
343
    struct jpeg_compress_struct cinfo;
343
    struct jpeg_compress_struct cinfo;
344
    struct my_error_mgr jerr;
344
    struct my_error_mgr jerr;
345
    /* More stuff */
345
    /* More stuff */
346
    JSAMPLE *pscanline, *scanline = (JSAMPLE *) calloc(3*width,sizeof(JSAMPLE));
346
    JSAMPLE *pscanline, *scanline = (JSAMPLE *) calloc(3*width,sizeof(JSAMPLE));
347
    int i, j;
347
    int i, j;
348
    unsigned int col;
348
    unsigned int col;
349
    DECLARESHIFTS;
349
    DECLARESHIFTS;
350
 
350
 
351
    /* Have we enough memory?*/
351
    /* Have we enough memory?*/
352
    if (scanline == NULL)
352
    if (scanline == NULL)
353
	return 0;
353
	return 0;
354
 
354
 
355
    if (outfile == NULL) {
355
    if (outfile == NULL) {
356
	free(scanline);
356
	free(scanline);
357
	return 0;
357
	return 0;
358
    }
358
    }
359
 
359
 
360
    /* Step 1: allocate and initialize JPEG compression object */
360
    /* Step 1: allocate and initialize JPEG compression object */
361
 
361
 
362
    /*
362
    /*
363
     * We set up the normal JPEG error routines, then override error_exit
363
     * We set up the normal JPEG error routines, then override error_exit
364
     * and output_message
364
     * and output_message
365
     */
365
     */
366
    cinfo.err = jpeg_std_error(&jerr.pub);
366
    cinfo.err = jpeg_std_error(&jerr.pub);
367
    jerr.pub.error_exit = my_error_exit ;
367
    jerr.pub.error_exit = my_error_exit ;
368
    jerr.pub.output_message = my_output_message ;
368
    jerr.pub.output_message = my_output_message ;
369
    /* Establish the setjmp return context for my_error_exit to use. */
369
    /* Establish the setjmp return context for my_error_exit to use. */
370
    if (setjmp(jerr.setjmp_buffer)) {
370
    if (setjmp(jerr.setjmp_buffer)) {
371
	/* If we get here, the JPEG code has signaled an error.
371
	/* If we get here, the JPEG code has signaled an error.
372
	 * We need to clean up the JPEG object, close the input file, and return.
372
	 * We need to clean up the JPEG object, close the input file, and return.
373
	 */
373
	 */
374
	jpeg_destroy_compress(&cinfo);
374
	jpeg_destroy_compress(&cinfo);
375
	free(scanline);
375
	free(scanline);
376
	if (outfile) fclose(outfile);
376
	if (outfile) fclose(outfile);
377
	return 0;
377
	return 0;
378
    }
378
    }
379
    /* Now we can initialize the JPEG compression object. */
379
    /* Now we can initialize the JPEG compression object. */
380
    jpeg_create_compress(&cinfo);
380
    jpeg_create_compress(&cinfo);
381
 
381
 
382
    /* Step 2: specify data destination (eg, a file) */
382
    /* Step 2: specify data destination (eg, a file) */
383
    jpeg_stdio_dest(&cinfo, outfile);
383
    jpeg_stdio_dest(&cinfo, outfile);
384
 
384
 
385
    /* Step 3: set parameters for compression */
385
    /* Step 3: set parameters for compression */
386
    /* First we supply a description of the input image.
386
    /* First we supply a description of the input image.
387
     * Four fields of the cinfo struct must be filled in:
387
     * Four fields of the cinfo struct must be filled in:
388
     */
388
     */
389
    cinfo.image_width = width;	/* image width and height, in pixels */
389
    cinfo.image_width = width;	/* image width and height, in pixels */
390
    cinfo.image_height = height;
390
    cinfo.image_height = height;
391
    cinfo.input_components = 3;		/* # of color components per pixel */
391
    cinfo.input_components = 3;		/* # of color components per pixel */
392
    cinfo.in_color_space = JCS_RGB;	/* colorspace of input image */
392
    cinfo.in_color_space = JCS_RGB;	/* colorspace of input image */
393
    jpeg_set_defaults(&cinfo);
393
    jpeg_set_defaults(&cinfo);
394
    if(res > 0) {
394
    if(res > 0) {
395
	cinfo.density_unit = 1;  /* pixels per inch */
395
	cinfo.density_unit = 1;  /* pixels per inch */
396
	cinfo.X_density = res;
396
	cinfo.X_density = res;
397
	cinfo.Y_density = res;
397
	cinfo.Y_density = res;
398
    }
398
    }
399
    jpeg_set_quality(&cinfo, quality, TRUE);
399
    jpeg_set_quality(&cinfo, quality, TRUE);
400
    /* Step 4: Start compressor */
400
    /* Step 4: Start compressor */
401
    jpeg_start_compress(&cinfo, TRUE);
401
    jpeg_start_compress(&cinfo, TRUE);
402
 
402
 
403
    /* Step 5: while (scan lines remain to be written) */
403
    /* Step 5: while (scan lines remain to be written) */
404
    /*           jpeg_write_scanlines(...); */
404
    /*           jpeg_write_scanlines(...); */
405
    for (i=0 ; i<height ; i++) {
405
    for (i=0 ; i<height ; i++) {
406
	/* Build the scanline */
406
	/* Build the scanline */
407
	pscanline = scanline;
407
	pscanline = scanline;
408
	for ( j=0 ; j<width ; j++) {
408
	for ( j=0 ; j<width ; j++) {
409
	    col = gp(d, i, j) & 0xFFFFFF;
409
	    col = gp(d, i, j) & 0xFFFFFF;
410
	    *pscanline++ = GETRED(col) ;
410
	    *pscanline++ = GETRED(col) ;
411
	    *pscanline++ = GETGREEN(col) ;
411
	    *pscanline++ = GETGREEN(col) ;
412
	    *pscanline++ = GETBLUE(col) ;
412
	    *pscanline++ = GETBLUE(col) ;
413
	}
413
	}
414
	jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &scanline, 1);
414
	jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &scanline, 1);
415
    }
415
    }
416
 
416
 
417
    /* Step 6: Finish compression */
417
    /* Step 6: Finish compression */
418
 
418
 
419
    jpeg_finish_compress(&cinfo);
419
    jpeg_finish_compress(&cinfo);
420
 
420
 
421
    /* Step 7: release JPEG compression object */
421
    /* Step 7: release JPEG compression object */
422
 
422
 
423
    /* This is an important step since it will release a good deal of memory. */
423
    /* This is an important step since it will release a good deal of memory. */
424
    free(scanline);
424
    free(scanline);
425
    jpeg_destroy_compress(&cinfo);
425
    jpeg_destroy_compress(&cinfo);
426
 
426
 
427
 
427
 
428
    /* And we're done! */
428
    /* And we're done! */
429
    return 1;
429
    return 1;
430
}
430
}
431
 
431
 
432
#endif /* HAVE_JPEG */
432
#endif /* HAVE_JPEG */
433
 
433
 
434
#ifdef HAVE_TIFF
434
#ifdef HAVE_TIFF
435
#include <tiffio.h>
435
#include <tiffio.h>
436
 
436
 
437
__declspec(dllexport)
437
__declspec(dllexport)
438
int R_SaveAsTIFF(void  *d, int width, int height,
438
int R_SaveAsTIFF(void  *d, int width, int height,
439
		unsigned int (*gp)(void *, int, int),
439
		unsigned int (*gp)(void *, int, int),
440
		int bgr, const char *outfile, int res, int compression)
440
		int bgr, const char *outfile, int res, int compression)
441
{
441
{
442
    TIFF *out;
442
    TIFF *out;
443
    int sampleperpixel;
443
    int sampleperpixel;
444
    tsize_t linebytes;
444
    tsize_t linebytes;
445
    unsigned char *buf, *pscanline;
445
    unsigned char *buf, *pscanline;
446
    unsigned int col, i, j;
446
    unsigned int col, i, j;
447
    int have_alpha = 0;
447
    int have_alpha = 0;
448
 
448
 
449
    DECLARESHIFTS;
449
    DECLARESHIFTS;
450
 
450
 
451
    for (i = 0; i < height; i++)
451
    for (i = 0; i < height; i++)
452
	for (j = 0; j < width; j++) {
452
	for (j = 0; j < width; j++) {
453
	    col = gp(d,i,j);
453
	    col = gp(d,i,j);
454
	    if (GETALPHA(col) < 255) {
454
	    if (GETALPHA(col) < 255) {
455
		have_alpha = 1;
455
		have_alpha = 1;
456
		break;
456
		break;
457
	    }
457
	    }
458
	}
458
	}
459
    sampleperpixel = 3 + have_alpha;
459
    sampleperpixel = 3 + have_alpha;
460
 
460
 
461
    out = TIFFOpen(outfile, "w");
461
    out = TIFFOpen(outfile, "w");
462
    if (!out) {
462
    if (!out) {
463
	warning("unable to open TIFF file '%s'", outfile);
463
	warning("unable to open TIFF file '%s'", outfile);
464
	return 0;
464
	return 0;
465
    }
465
    }
466
    TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
466
    TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
467
    TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
467
    TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
468
    TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, sampleperpixel);
468
    TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, sampleperpixel);
469
    TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
469
    TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
470
    TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
470
    TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
471
    TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
471
    TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
472
    TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
472
    TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
473
#if 0
473
#if 0
474
    /* Possible compression values
474
    /* Possible compression values
475
       COMPRESSION_NONE = 1;
475
       COMPRESSION_NONE = 1;
476
       COMPRESSION_CCITTRLE = 2;
476
       COMPRESSION_CCITTRLE = 2;
477
       COMPRESSION_CCITTFAX3 = COMPRESSION_CCITT_T4 = 3;
477
       COMPRESSION_CCITTFAX3 = COMPRESSION_CCITT_T4 = 3;
478
       COMPRESSION_CCITTFAX4 = COMPRESSION_CCITT_T6 = 4;
478
       COMPRESSION_CCITTFAX4 = COMPRESSION_CCITT_T6 = 4;
479
       COMPRESSION_LZW = 5;
479
       COMPRESSION_LZW = 5;
480
       COMPRESSION_JPEG = 7;
480
       COMPRESSION_JPEG = 7;
481
       COMPRESSION_DEFLATE = 32946;
481
       COMPRESSION_DEFLATE = 32946;
482
       COMPRESSION_ADOBE_DEFLATE = 8;
482
       COMPRESSION_ADOBE_DEFLATE = 8;
483
    */
483
    */
484
    TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
484
    TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
485
#endif
485
#endif
486
    if(compression > 1)
486
    if(compression > 1)
487
	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
487
	TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
488
 
488
 
489
    if (res > 0) {
489
    if (res > 0) {
490
	TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
490
	TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
491
	TIFFSetField(out, TIFFTAG_XRESOLUTION, (float) res);
491
	TIFFSetField(out, TIFFTAG_XRESOLUTION, (float) res);
492
	TIFFSetField(out, TIFFTAG_YRESOLUTION, (float) res);
492
	TIFFSetField(out, TIFFTAG_YRESOLUTION, (float) res);
493
    }
493
    }
494
 
494
 
495
    linebytes = sampleperpixel * width;
495
    linebytes = sampleperpixel * width;
496
    if (TIFFScanlineSize(out))
496
    if (TIFFScanlineSize(out))
497
	buf =(unsigned char *)_TIFFmalloc(linebytes);
497
	buf =(unsigned char *)_TIFFmalloc(linebytes);
498
    else
498
    else
499
	buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
499
	buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
500
 
500
 
501
    for (i = 0; i < height; i++) {
501
    for (i = 0; i < height; i++) {
502
	pscanline = buf;
502
	pscanline = buf;
503
	for(j = 0; j < width; j++) {
503
	for(j = 0; j < width; j++) {
504
	    col = gp(d, i, j);
504
	    col = gp(d, i, j);
505
	    *pscanline++ = GETRED(col) ;
505
	    *pscanline++ = GETRED(col) ;
506
	    *pscanline++ = GETGREEN(col) ;
506
	    *pscanline++ = GETGREEN(col) ;
507
	    *pscanline++ = GETBLUE(col) ;
507
	    *pscanline++ = GETBLUE(col) ;
508
	    if(have_alpha) *pscanline++ = GETALPHA(col) ;
508
	    if(have_alpha) *pscanline++ = GETALPHA(col) ;
509
	}
509
	}
510
	TIFFWriteScanline(out, buf, i, 0);
510
	TIFFWriteScanline(out, buf, i, 0);
511
    }
511
    }
512
    TIFFClose(out);
512
    TIFFClose(out);
513
    _TIFFfree(buf);
513
    _TIFFfree(buf);
514
    return 1;
514
    return 1;
515
}
515
}
516
#endif  /* HAVE_TIFF */
516
#endif  /* HAVE_TIFF */
517
 
517
 
518
 
518
 
519
/*
519
/*
520
 * Try to save the content of the device 'd' in 'filename' as Windows BMP.
520
 * Try to save the content of the device 'd' in 'filename' as Windows BMP.
521
 * If numbers of colors is less than 256 we use a 'palette' BMP.
521
 * If numbers of colors is less than 256 we use a 'palette' BMP.
522
 * Return 1 on success, 0 on failure
522
 * Return 1 on success, 0 on failure
523
*/
523
*/
524
 
524
 
525
#define BMPERROR {R_ShowMessage("Problems writing to 'bmp' file");return 0;}
525
#define BMPERROR {R_ShowMessage("Problems writing to 'bmp' file");return 0;}
526
#define BMPW(a) {wrd=a;if(fwrite(&wrd,sizeof(unsigned short),1,fp)!=1) BMPERROR}
526
#define BMPW(a) {wrd=a;if(fwrite(&wrd,sizeof(unsigned short),1,fp)!=1) BMPERROR}
527
#define BMPDW(a) {dwrd=a;if(fwrite(&dwrd,sizeof(unsigned int),1,fp)!=1) BMPERROR}
527
#define BMPDW(a) {dwrd=a;if(fwrite(&dwrd,sizeof(unsigned int),1,fp)!=1) BMPERROR}
528
#define BMPPUTC(a) if(fputc(a,fp)==EOF) BMPERROR;
528
#define BMPPUTC(a) if(fputc(a,fp)==EOF) BMPERROR;
529
#define HEADERSIZE 54
529
#define HEADERSIZE 54
530
 
530
 
531
__declspec(dllexport)
531
__declspec(dllexport)
532
int R_SaveAsBmp(void  *d, int width, int height,
532
int R_SaveAsBmp(void  *d, int width, int height,
533
		unsigned int (*gp)(void *, int, int), int bgr, FILE *fp,
533
		unsigned int (*gp)(void *, int, int), int bgr, FILE *fp,
534
		int res)
534
		int res)
535
{
535
{
536
    unsigned int  col, palette[256];
536
    unsigned int  col, palette[256];
537
    int i, j, r, ncols, mid, high, low, withpalette;
537
    int i, j, r, ncols, mid, high, low, withpalette;
538
    int bfOffBits, bfSize, biBitCount, biClrUsed , pad;
538
    int bfOffBits, bfSize, biBitCount, biClrUsed , pad;
539
    unsigned short wrd;
539
    unsigned short wrd;
540
    unsigned int dwrd;
540
    unsigned int dwrd;
541
    int lres;
541
    int lres;
542
    DECLARESHIFTS;
542
    DECLARESHIFTS;
543
 
543
 
544
    if (fp == NULL)
544
    if (fp == NULL)
545
	return 0;
545
	return 0;
546
 
546
 
547
    /* Have we less than 256 different colors? */
547
    /* Have we less than 256 different colors? */
548
    ncols = mid = 0;
548
    ncols = mid = 0;
549
    withpalette = 1;
549
    withpalette = 1;
550
    for (i = 0; i < 256 ; i++) palette[i] = 0;
550
    for (i = 0; i < 256 ; i++) palette[i] = 0;
551
    for (i = 0; (i < height) && withpalette ; i++) {
551
    for (i = 0; (i < height) && withpalette ; i++) {
552
	for (j = 0; (j < width) && withpalette ; j++) {
552
	for (j = 0; (j < width) && withpalette ; j++) {
553
	    col = gp(d,i,j) & 0xFFFFFF ;
553
	    col = gp(d,i,j) & 0xFFFFFF ;
554
	    /* binary search the palette: */
554
	    /* binary search the palette: */
555
	    low = 0;
555
	    low = 0;
556
	    high = ncols - 1;
556
	    high = ncols - 1;
557
	    while (low <= high) {
557
	    while (low <= high) {
558
		mid = (low + high)/2;
558
		mid = (low + high)/2;
559
		if ( col < palette[mid] ) high = mid - 1;
559
		if ( col < palette[mid] ) high = mid - 1;
560
		else if ( col > palette[mid] ) low  = mid + 1;
560
		else if ( col > palette[mid] ) low  = mid + 1;
561
		else break;
561
		else break;
562
	    }
562
	    }
563
	    if (high < low) {
563
	    if (high < low) {
564
		/* didn't find colour in palette, insert it: */
564
		/* didn't find colour in palette, insert it: */
565
		if (ncols >= 256) {
565
		if (ncols >= 256) {
566
		    withpalette = 0;
566
		    withpalette = 0;
567
		} else {
567
		} else {
568
		    for (r = ncols; r > low; r--)
568
		    for (r = ncols; r > low; r--)
569
			palette[r] = palette[r-1] ;
569
			palette[r] = palette[r-1] ;
570
		    palette[low] = col;
570
		    palette[low] = col;
571
		    ncols ++;
571
		    ncols ++;
572
		}
572
		}
573
	    }
573
	    }
574
	}
574
	}
575
    }
575
    }
576
    /* Compute some part of the header */
576
    /* Compute some part of the header */
577
    if (withpalette) {
577
    if (withpalette) {
578
	bfOffBits = HEADERSIZE + 4 * 256;
578
	bfOffBits = HEADERSIZE + 4 * 256;
579
	bfSize = bfOffBits + width * height ;
579
	bfSize = bfOffBits + width * height ;
580
	biBitCount = 8;
580
	biBitCount = 8;
581
	biClrUsed = 256;
581
	biClrUsed = 256;
582
    } else {
582
    } else {
583
	bfOffBits = HEADERSIZE + 4;
583
	bfOffBits = HEADERSIZE + 4;
584
	bfSize = bfOffBits + 3 * width * height ;
584
	bfSize = bfOffBits + 3 * width * height ;
585
	biBitCount = 24;
585
	biBitCount = 24;
586
	biClrUsed = 0;
586
	biClrUsed = 0;
587
    }
587
    }
588
 
588
 
589
    /* write the header */
589
    /* write the header */
590
 
590
 
591
    BMPPUTC('B');BMPPUTC('M');
591
    BMPPUTC('B');BMPPUTC('M');
592
    BMPDW(bfSize); /*bfSize*/
592
    BMPDW(bfSize); /*bfSize*/
593
    BMPW(0);BMPW(0); /* bfReserved1 and bfReserved2 must be 0*/
593
    BMPW(0);BMPW(0); /* bfReserved1 and bfReserved2 must be 0*/
594
    BMPDW(bfOffBits); /* bfOffBits */
594
    BMPDW(bfOffBits); /* bfOffBits */
595
    BMPDW(40);	/* Windows V3. size 40 bytes */
595
    BMPDW(40);	/* Windows V3. size 40 bytes */
596
    BMPDW(width); /* biWidth */
596
    BMPDW(width); /* biWidth */
597
    BMPDW(height); /* biHeight */
597
    BMPDW(height); /* biHeight */
598
    BMPW(1);	/* biPlanes - must be 1 */
598
    BMPW(1);	/* biPlanes - must be 1 */
599
    BMPW(biBitCount); /* biBitCount */
599
    BMPW(biBitCount); /* biBitCount */
600
    BMPDW(0); /* biCompression=BI_RGB */
600
    BMPDW(0); /* biCompression=BI_RGB */
601
    BMPDW(0); /* biSizeImage (with BI_RGB not needed)*/
601
    BMPDW(0); /* biSizeImage (with BI_RGB not needed)*/
602
    lres = (int)(0.5 + res/0.0254);
602
    lres = (int)(0.5 + res/0.0254);
603
    BMPDW(lres); /* XPels/M */
603
    BMPDW(lres); /* XPels/M */
604
    BMPDW(lres); /* XPels/M */
604
    BMPDW(lres); /* XPels/M */
605
    BMPDW(biClrUsed); /* biClrUsed */
605
    BMPDW(biClrUsed); /* biClrUsed */
606
    BMPDW(0) ; /* biClrImportant All colours are important */
606
    BMPDW(0) ; /* biClrImportant All colours are important */
607
 
607
 
608
    /* and now the image */
608
    /* and now the image */
609
    if (withpalette) {
609
    if (withpalette) {
610
	/* 8 bit image; write the palette */
610
	/* 8 bit image; write the palette */
611
	for (i = 0; i < 256; i++) {
611
	for (i = 0; i < 256; i++) {
612
	    col = palette[i];
612
	    col = palette[i];
613
	    BMPPUTC(GETBLUE(col));
613
	    BMPPUTC(GETBLUE(col));
614
	    BMPPUTC(GETGREEN(col));
614
	    BMPPUTC(GETGREEN(col));
615
	    BMPPUTC(GETRED(col));
615
	    BMPPUTC(GETRED(col));
616
	    BMPPUTC(0);
616
	    BMPPUTC(0);
617
	}
617
	}
618
	/* Rows must be padded to 4-byte boundary */
618
	/* Rows must be padded to 4-byte boundary */
619
	for (pad = 0; ((width+pad) & 3) != 0; pad++);
619
	for (pad = 0; ((width+pad) & 3) != 0; pad++);
620
	/* and then the pixels */
620
	/* and then the pixels */
621
	for (i = height-1 ; i >= 0 ; i--) {
621
	for (i = height-1 ; i >= 0 ; i--) {
622
	    for (j = 0 ; j < width ; j++) {
622
	    for (j = 0 ; j < width ; j++) {
623
		col = gp(d, i, j) & 0xFFFFFF;
623
		col = gp(d, i, j) & 0xFFFFFF;
624
		/* binary search the palette (the colour must be there): */
624
		/* binary search the palette (the colour must be there): */
625
		low = 0;  high = ncols - 1;
625
		low = 0;  high = ncols - 1;
626
		while (low <= high) {
626
		while (low <= high) {
627
		    mid = (low + high)/2;
627
		    mid = (low + high)/2;
628
		    if      (col < palette[mid]) high = mid - 1;
628
		    if      (col < palette[mid]) high = mid - 1;
629
		    else if (col > palette[mid]) low  = mid + 1;
629
		    else if (col > palette[mid]) low  = mid + 1;
630
		    else break;
630
		    else break;
631
		}
631
		}
632
		BMPPUTC(mid);
632
		BMPPUTC(mid);
633
	    }
633
	    }
634
	    for (j = 0; j < pad; j++) BMPPUTC(0);
634
	    for (j = 0; j < pad; j++) BMPPUTC(0);
635
	}
635
	}
636
    } else {
636
    } else {
637
	/* 24 bits image */
637
	/* 24 bits image */
638
	BMPDW(0); /* null bmiColors */
638
	BMPDW(0); /* null bmiColors */
639
	for (pad = 0; ((3*width+pad) & 3) != 0; pad++); /*padding*/
639
	for (pad = 0; ((3*width+pad) & 3) != 0; pad++); /*padding*/
640
	for (i = height-1 ; i>=0 ; i--) {
640
	for (i = height-1 ; i>=0 ; i--) {
641
	    for (j = 0 ; j < width ; j++) {
641
	    for (j = 0 ; j < width ; j++) {
642
		col = gp(d, i, j) & 0xFFFFFF;
642
		col = gp(d, i, j) & 0xFFFFFF;
643
		BMPPUTC(GETBLUE(col));
643
		BMPPUTC(GETBLUE(col));
644
		BMPPUTC(GETGREEN(col));
644
		BMPPUTC(GETGREEN(col));
645
		BMPPUTC(GETRED(col));
645
		BMPPUTC(GETRED(col));
646
	    }
646
	    }
647
	    for (j = 0; j < pad; j++) BMPPUTC(0);
647
	    for (j = 0; j < pad; j++) BMPPUTC(0);
648
	}
648
	}
649
    }
649
    }
650
    return 1;
650
    return 1;
651
}
651
}