The R Project SVN R

Rev

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

Rev 29909 Rev 30104
1
/*
1
/*
2
 *  R : A Computer Language for Statistical Data Analysis
2
 *  R : A Computer Language for Statistical Data Analysis
3
 *  Copyright (C) 1999, 2001, 2004  Guido Masarotto and the R Development Core Team
3
 *  Copyright (C) 1999, 2001, 2004  Guido Masarotto and the R Development 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, write to the Free Software
16
 *  along with this program; if not, write to the Free Software
17
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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 long (*gp)(void *d, int x, int y): a function which
26
 * unsigned long (*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 include/Graphics.h) or as RGB in the
28
 *     BGR (R model, see include/Graphics.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) & 0xFFUL)
44
#define GETRED(col)    (((col) >> RSHIFT) & 0xFFUL)
45
#define GETGREEN(col)  (((col) >> GSHIFT) & 0xFFUL)
45
#define GETGREEN(col)  (((col) >> GSHIFT) & 0xFFUL)
46
#define GETBLUE(col)   (((col) >> BSHIFT) & 0xFFUL)
46
#define GETBLUE(col)   (((col) >> BSHIFT) & 0xFFUL)
47
 
47
 
48
#include <R_ext/Error.h>
48
#include <R_ext/Error.h>
49
 
49
 
50
#ifdef HAVE_PNG
50
#ifdef HAVE_PNG
51
 
51
 
52
#include "png.h"
52
#include "png.h"
53
/* 
53
/* 
54
 * Try to save the content of the device 'd' in 'filename' as png.
54
 * Try to save the content of the device 'd' in 'filename' as png.
55
 * If numbers of colors is less than 256 we use a 'palette' png.
55
 * If numbers of colors is less than 256 we use a 'palette' png.
56
 * Return 1 on success, 0 on failure 
56
 * Return 1 on success, 0 on failure 
57
*/
57
*/
58
 
58
 
59
/*  
59
/*  
60
    I don't use 'error' since (1) we must free 'scanline' and 
60
    I don't use 'error' since (1) we must free 'scanline' and 
61
   (2) we can be arrived here from a button or menuitem callback maybe
61
   (2) we can be arrived here from a button or menuitem callback maybe
62
   in a different thread from the one where R runs.
62
   in a different thread from the one where R runs.
63
*/ 
63
*/ 
64
static void my_png_error(png_structp png_ptr, png_const_charp msg) 
64
static void my_png_error(png_structp png_ptr, png_const_charp msg) 
65
{
65
{
66
  R_ShowMessage((char *) msg);
66
  R_ShowMessage((char *) msg);
67
  longjmp(png_ptr->jmpbuf,1);
67
  longjmp(png_ptr->jmpbuf,1);
68
}
68
}
69
 
69
 
70
static void my_png_warning(png_structp png_ptr, png_const_charp msg) 
70
static void my_png_warning(png_structp png_ptr, png_const_charp msg) 
71
{
71
{
72
  warning("libpng: %s",(char *) msg);
72
  warning("libpng: %s",(char *) msg);
73
}
73
}
74
 
74
 
75
#define CN (100.0/2.54)
75
#define CN (100.0/2.54)
76
 
76
 
77
int R_SaveAsPng(void  *d, int width, int height, 
77
int R_SaveAsPng(void  *d, int width, int height, 
78
		unsigned long (*gp)(void *, int, int),
78
		unsigned long (*gp)(void *, int, int),
79
		int bgr, FILE *fp, unsigned int transparent, int res) 
79
		int bgr, FILE *fp, unsigned int transparent, int res) 
80
{
80
{
81
  png_structp png_ptr;
81
  png_structp png_ptr;
82
  png_infop info_ptr;
82
  png_infop info_ptr;
83
  unsigned long  col, palette[256];
83
  unsigned long  col, palette[256];
84
  png_color pngpalette[256];
84
  png_color pngpalette[256];
85
  png_bytep pscanline, scanline = calloc(3*width,sizeof(png_byte));
85
  png_bytep pscanline, scanline = calloc(3*width,sizeof(png_byte));
86
  png_byte trans[256];
86
  png_byte trans[256];
87
  png_color_16 trans_values[1];
87
  png_color_16 trans_values[1];
88
  int i, j, r, ncols, mid, high, low, withpalette;
88
  int i, j, r, ncols, mid, high, low, withpalette;
89
  DECLARESHIFTS;
89
  DECLARESHIFTS;
90
 
90
 
91
  /* Have we enough memory?*/
91
  /* Have we enough memory?*/
92
  if (scanline == NULL) 
92
  if (scanline == NULL) 
93
    return 0;
93
    return 0;
94
 
94
 
95
  /* Create and initialize the png_struct with the desired error handler
95
  /* Create and initialize the png_struct with the desired error handler
96
   * functions.  If you want to use the default stderr and longjump method,
96
   * functions.  If you want to use the default stderr and longjump method,
97
   * you can supply NULL for the last three parameters.  We also check that
97
   * you can supply NULL for the last three parameters.  We also check that
98
   * the library version is compatible with the one used at compile time,
98
   * the library version is compatible with the one used at compile time,
99
   * in case we are using dynamically linked libraries.  REQUIRED.
99
   * in case we are using dynamically linked libraries.  REQUIRED.
100
   */
100
   */
101
  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
101
  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
102
  if (png_ptr == NULL) {
102
  if (png_ptr == NULL) {
103
    free(scanline);
103
    free(scanline);
104
    return 0;
104
    return 0;
105
  }
105
  }
106
 
106
 
107
  /* Allocate/initialize the image information data.  REQUIRED */
107
  /* Allocate/initialize the image information data.  REQUIRED */
108
  info_ptr = png_create_info_struct(png_ptr);
108
  info_ptr = png_create_info_struct(png_ptr);
109
  if (info_ptr == NULL) {
109
  if (info_ptr == NULL) {
110
    free(scanline);
110
    free(scanline);
111
    png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
111
    png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
112
    return 0;
112
    return 0;
113
  }
113
  }
114
  
114
  
115
  /* Set error handling.  REQUIRED if you aren't supplying your own
115
  /* Set error handling.  REQUIRED if you aren't supplying your own
116
   * error handling functions in the png_create_write_struct() call.
116
   * error handling functions in the png_create_write_struct() call.
117
   */
117
   */
118
  if (setjmp(png_ptr->jmpbuf)) {
118
  if (setjmp(png_ptr->jmpbuf)) {
119
    /* If we get here, we had a problem writing the file */
119
    /* If we get here, we had a problem writing the file */
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
  png_set_error_fn(png_ptr, NULL, my_png_error, my_png_warning);
124
  png_set_error_fn(png_ptr, NULL, my_png_error, my_png_warning);
125
  
125
  
126
  /* I/O initialization functions is REQUIRED */
126
  /* I/O initialization functions is REQUIRED */
127
  png_init_io(png_ptr, fp);
127
  png_init_io(png_ptr, fp);
128
  /* Have we less than 256 different colors? */
128
  /* Have we less than 256 different colors? */
129
  ncols = 0;
129
  ncols = 0;
130
  if(transparent) palette[ncols++] = transparent & 0xFFFFFFUL;
130
  if(transparent) palette[ncols++] = transparent & 0xFFFFFFUL;
131
  mid = ncols;
131
  mid = ncols;
132
  withpalette = 1;
132
  withpalette = 1;
133
  for (i = 0; (i < height) && withpalette ; i++) {
133
  for (i = 0; (i < height) && withpalette ; i++) {
134
    for (j = 0; (j < width) && withpalette ; j++) {
134
    for (j = 0; (j < width) && withpalette ; j++) {
135
      col = gp(d,i,j) & 0xFFFFFFUL ;
135
      col = gp(d,i,j) & 0xFFFFFFUL ;
136
      /* binary search the palette: */
136
      /* binary search the palette: */
137
      low = 0;  
137
      low = 0;  
138
      high = ncols - 1;
138
      high = ncols - 1;
139
      while (low <= high) {
139
      while (low <= high) {
140
	mid = (low + high)/2;
140
	mid = (low + high)/2;
141
	if ( col < palette[mid] ) high = mid - 1;
141
	if ( col < palette[mid] ) high = mid - 1;
142
	else if ( col > palette[mid] ) low  = mid + 1;
142
	else if ( col > palette[mid] ) low  = mid + 1;
143
	else break;
143
	else break;
144
      }
144
      }
145
      if (high < low) {
145
      if (high < low) {
146
	/* didn't find colour in palette, insert it: */
146
	/* didn't find colour in palette, insert it: */
147
	if (ncols >= 256) {
147
	if (ncols >= 256) {
148
	  withpalette = 0;
148
	  withpalette = 0;
149
	} else {
149
	} else {
150
	  for (r = ncols; r > low; r--)
150
	  for (r = ncols; r > low; r--)
151
	    palette[r] = palette[r-1] ;
151
	    palette[r] = palette[r-1] ;
152
	  palette[low] = col;
152
	  palette[low] = col;
153
	  ncols ++;
153
	  ncols ++;
154
	}
154
	}
155
      }
155
      }
156
    }
156
    }
157
  }
157
  }
158
 
158
 
159
  /* Set the image information here.  Width and height are up to 2^31,
159
  /* Set the image information here.  Width and height are up to 2^31,
160
   * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
160
   * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
161
   * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
161
   * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
162
   * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
162
   * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
163
   * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
163
   * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
164
   * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
164
   * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
165
   * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
165
   * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
166
   */
166
   */
167
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, 
167
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, 
168
	       withpalette ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
168
	       withpalette ? PNG_COLOR_TYPE_PALETTE : PNG_COLOR_TYPE_RGB,
169
	       PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, 
169
	       PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, 
170
	       PNG_FILTER_TYPE_BASE);
170
	       PNG_FILTER_TYPE_BASE);
171
 
171
 
172
  if (withpalette) {
172
  if (withpalette) {
173
    for (i = 0; i < ncols ; i++) {
173
    for (i = 0; i < ncols ; i++) {
174
      col = palette[i];
174
      col = palette[i];
175
      pngpalette[i].red = GETRED(col);
175
      pngpalette[i].red = GETRED(col);
176
      pngpalette[i].green = GETGREEN(col);
176
      pngpalette[i].green = GETGREEN(col);
177
      pngpalette[i].blue = GETBLUE(col);
177
      pngpalette[i].blue = GETBLUE(col);
178
    } 
178
    } 
179
    png_set_PLTE(png_ptr, info_ptr, pngpalette, ncols);
179
    png_set_PLTE(png_ptr, info_ptr, pngpalette, ncols);
180
  } 
180
  } 
181
  /* Deal with transparency */
181
  /* Deal with transparency */
182
  if(transparent) {
182
  if(transparent) {
183
      if(withpalette) {
183
      if(withpalette) {
184
	  for (i = 0; i < ncols ; i++)
184
	  for (i = 0; i < ncols ; i++)
185
	      trans[i] = (palette[i] == (transparent & 0xFFFFFFUL)) ? 0:255;
185
	      trans[i] = (palette[i] == (transparent & 0xFFFFFFUL)) ? 0:255;
186
      } else {
186
      } else {
187
	  trans_values[0].red = GETRED(transparent);
187
	  trans_values[0].red = GETRED(transparent);
188
	  trans_values[0].blue = GETBLUE(transparent);
188
	  trans_values[0].blue = GETBLUE(transparent);
189
	  trans_values[0].green = GETGREEN(transparent);
189
	  trans_values[0].green = GETGREEN(transparent);
190
      }
190
      }
191
      png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
191
      png_set_tRNS(png_ptr, info_ptr, trans, ncols, trans_values);
192
  }
192
  }
193
 
193
 
194
  if(res > 0) 
194
  if(res > 0) 
195
      png_set_pHYs(png_ptr, info_ptr, res/0.0254, res/0.0254,
195
      png_set_pHYs(png_ptr, info_ptr, res/0.0254, res/0.0254,
196
		   PNG_RESOLUTION_METER);
196
		   PNG_RESOLUTION_METER);
197
 
197
 
198
  /* Write the file header information.  REQUIRED */
198
  /* Write the file header information.  REQUIRED */
199
  png_write_info(png_ptr, info_ptr);
199
  png_write_info(png_ptr, info_ptr);
200
 
200
 
201
  /* 
201
  /* 
202
   * Now, write the pixels
202
   * Now, write the pixels
203
   */
203
   */
204
  for (i=0 ; i<height ; i++) { 
204
  for (i=0 ; i<height ; i++) { 
205
    /* Build the scanline */
205
    /* Build the scanline */
206
    pscanline = scanline;
206
    pscanline = scanline;
207
    for ( j=0 ; j<width ; j++) {
207
    for ( j=0 ; j<width ; j++) {
208
      col = gp(d, i, j);
208
      col = gp(d, i, j);
209
      if (withpalette) { 
209
      if (withpalette) { 
210
	    /* binary search the palette (the colour must be there): */
210
	    /* binary search the palette (the colour must be there): */
211
	    low = 0;  high = ncols - 1;
211
	    low = 0;  high = ncols - 1;
212
	    while (low <= high) {
212
	    while (low <= high) {
213
		mid = (low + high)/2;
213
		mid = (low + high)/2;
214
		if      (col < palette[mid]) high = mid - 1;
214
		if      (col < palette[mid]) high = mid - 1;
215
		else if (col > palette[mid]) low  = mid + 1;
215
		else if (col > palette[mid]) low  = mid + 1;
216
		else break;
216
		else break;
217
	    }
217
	    }
218
	    *pscanline++ = mid;
218
	    *pscanline++ = mid;
219
      } else { 
219
      } else { 
220
	*pscanline++ = GETRED(col) ;
220
	*pscanline++ = GETRED(col) ;
221
        *pscanline++ = GETGREEN(col) ;
221
        *pscanline++ = GETGREEN(col) ;
222
        *pscanline++ = GETBLUE(col) ;
222
        *pscanline++ = GETBLUE(col) ;
223
      }
223
      }
224
    }
224
    }
225
    png_write_row(png_ptr, scanline);
225
    png_write_row(png_ptr, scanline);
226
  } 
226
  } 
227
 
227
 
228
  /* It is REQUIRED to call this to finish writing the rest of the file */
228
  /* It is REQUIRED to call this to finish writing the rest of the file */
229
  png_write_end(png_ptr, info_ptr);
229
  png_write_end(png_ptr, info_ptr);
230
  
230
  
231
  /* clean up after the write, and free any memory allocated */
231
  /* clean up after the write, and free any memory allocated */
232
  free(scanline);
232
  free(scanline);
233
  png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
233
  png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
234
 
234
 
235
  /* that's it */
235
  /* that's it */
236
  return 1;
236
  return 1;
237
}
237
}
238
 
238
 
239
#endif /* HAVE_PNG */
239
#endif /* HAVE_PNG */
240
 
240
 
241
 
241
 
242
#ifdef HAVE_JPEG 
242
#ifdef HAVE_JPEG 
243
 
243
 
244
#include <jpeglib.h>
244
#include <jpeglib.h>
245
 
245
 
246
/* Here's the extended error handler struct */
246
/* Here's the extended error handler struct */
247
 
247
 
248
struct my_error_mgr {
248
struct my_error_mgr {
249
  struct jpeg_error_mgr pub;	/* "public" fields */
249
  struct jpeg_error_mgr pub;	/* "public" fields */
250
  jmp_buf setjmp_buffer;	/* for return to caller */
250
  jmp_buf setjmp_buffer;	/* for return to caller */
251
};
251
};
252
 
252
 
253
typedef struct my_error_mgr * my_error_ptr;
253
typedef struct my_error_mgr * my_error_ptr;
254
 
254
 
255
/*
255
/*
256
 * Here's the routine that will replace the standard error_exit method:
256
 * Here's the routine that will replace the standard error_exit method:
257
*/
257
*/
258
 
258
 
259
static void my_error_exit (j_common_ptr cinfo)
259
static void my_error_exit (j_common_ptr cinfo)
260
{
260
{
261
  /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
261
  /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
262
  my_error_ptr myerr = (my_error_ptr) cinfo->err;
262
  my_error_ptr myerr = (my_error_ptr) cinfo->err;
263
 
263
 
264
  /* Always display the message. */
264
  /* Always display the message. */
265
  (*cinfo->err->output_message) (cinfo);
265
  (*cinfo->err->output_message) (cinfo);
266
 
266
 
267
  /* Return control to the setjmp point */
267
  /* Return control to the setjmp point */
268
  longjmp(myerr->setjmp_buffer, 1);
268
  longjmp(myerr->setjmp_buffer, 1);
269
}
269
}
270
 
270
 
271
/* We also replace the output method */
271
/* We also replace the output method */
272
static void my_output_message (j_common_ptr cinfo)
272
static void my_output_message (j_common_ptr cinfo)
273
{
273
{
274
  char buffer[JMSG_LENGTH_MAX];
274
  char buffer[JMSG_LENGTH_MAX];
275
 
275
 
276
  /* Create the message */
276
  /* Create the message */
277
  (*cinfo->err->format_message) (cinfo, buffer);
277
  (*cinfo->err->format_message) (cinfo, buffer);
278
 
278
 
279
  /* and show it */  
279
  /* and show it */  
280
  R_ShowMessage(buffer);
280
  R_ShowMessage(buffer);
281
}
281
}
282
 
282
 
283
 
283
 
284
 
284
 
285
int R_SaveAsJpeg(void  *d, int width, int height, 
285
int R_SaveAsJpeg(void  *d, int width, int height, 
286
		unsigned long (*gp)(void *, int, int),
286
		unsigned long (*gp)(void *, int, int),
287
		int bgr, int quality, FILE *outfile, int res) 
287
		int bgr, int quality, FILE *outfile, int res) 
288
{
288
{
289
  struct jpeg_compress_struct cinfo;
289
  struct jpeg_compress_struct cinfo;
290
  struct my_error_mgr jerr;
290
  struct my_error_mgr jerr;
291
  /* More stuff */
291
  /* More stuff */
292
  JSAMPLE *pscanline, *scanline = calloc(3*width,sizeof(JSAMPLE));
292
  JSAMPLE *pscanline, *scanline = calloc(3*width,sizeof(JSAMPLE));
293
  int i, j;
293
  int i, j;
294
  unsigned long col;
294
  unsigned long col;
295
  DECLARESHIFTS;
295
  DECLARESHIFTS;
296
 
296
 
297
  /* Have we enough memory?*/
297
  /* Have we enough memory?*/
298
  if (scanline == NULL) 
298
  if (scanline == NULL) 
299
    return 0;
299
    return 0;
300
 
300
 
301
  /* Step 1: allocate and initialize JPEG compression object */
301
  /* Step 1: allocate and initialize JPEG compression object */
302
 
302
 
303
  /* 
303
  /* 
304
   * We set up the normal JPEG error routines, then override error_exit
304
   * We set up the normal JPEG error routines, then override error_exit
305
   * and output_message
305
   * and output_message
306
  */
306
  */
307
  cinfo.err = jpeg_std_error(&jerr.pub);
307
  cinfo.err = jpeg_std_error(&jerr.pub);
308
  jerr.pub.error_exit = my_error_exit ;
308
  jerr.pub.error_exit = my_error_exit ;
309
  jerr.pub.output_message = my_output_message ;
309
  jerr.pub.output_message = my_output_message ;
310
  /* Establish the setjmp return context for my_error_exit to use. */
310
  /* Establish the setjmp return context for my_error_exit to use. */
311
  if (setjmp(jerr.setjmp_buffer)) {
311
  if (setjmp(jerr.setjmp_buffer)) {
312
    /* If we get here, the JPEG code has signaled an error.
312
    /* If we get here, the JPEG code has signaled an error.
313
     * We need to clean up the JPEG object, close the input file, and return.
313
     * We need to clean up the JPEG object, close the input file, and return.
314
     */
314
     */
315
    jpeg_destroy_compress(&cinfo);
315
    jpeg_destroy_compress(&cinfo);
316
    free(scanline);
316
    free(scanline);
317
    if (outfile) fclose(outfile);
317
    if (outfile) fclose(outfile);
318
    return 0;
318
    return 0;
319
  }
319
  }
320
  /* Now we can initialize the JPEG compression object. */
320
  /* Now we can initialize the JPEG compression object. */
321
  jpeg_create_compress(&cinfo);
321
  jpeg_create_compress(&cinfo);
322
 
322
 
323
  /* Step 2: specify data destination (eg, a file) */
323
  /* Step 2: specify data destination (eg, a file) */
324
  jpeg_stdio_dest(&cinfo, outfile);
324
  jpeg_stdio_dest(&cinfo, outfile);
325
 
325
 
326
  /* Step 3: set parameters for compression */
326
  /* Step 3: set parameters for compression */
327
  /* First we supply a description of the input image.
327
  /* First we supply a description of the input image.
328
   * Four fields of the cinfo struct must be filled in:
328
   * Four fields of the cinfo struct must be filled in:
329
   */
329
   */
330
  cinfo.image_width = width; 	/* image width and height, in pixels */
330
  cinfo.image_width = width; 	/* image width and height, in pixels */
331
  cinfo.image_height = height;
331
  cinfo.image_height = height;
332
  cinfo.input_components = 3;		/* # of color components per pixel */
332
  cinfo.input_components = 3;		/* # of color components per pixel */
333
  cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */
333
  cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */
334
  jpeg_set_defaults(&cinfo);
334
  jpeg_set_defaults(&cinfo);
335
  if(res > 0) {
335
  if(res > 0) {
336
      cinfo.density_unit = 1;  /* pixels per inch */
336
      cinfo.density_unit = 1;  /* pixels per inch */
337
      cinfo.X_density = res;
337
      cinfo.X_density = res;
338
      cinfo.Y_density = res;
338
      cinfo.Y_density = res;
339
  }
339
  }
340
  jpeg_set_quality(&cinfo, quality, TRUE);
340
  jpeg_set_quality(&cinfo, quality, TRUE);
341
  /* Step 4: Start compressor */
341
  /* Step 4: Start compressor */
342
  jpeg_start_compress(&cinfo, TRUE);
342
  jpeg_start_compress(&cinfo, TRUE);
343
 
343
 
344
  /* Step 5: while (scan lines remain to be written) */
344
  /* Step 5: while (scan lines remain to be written) */
345
  /*           jpeg_write_scanlines(...); */
345
  /*           jpeg_write_scanlines(...); */
346
  for (i=0 ; i<height ; i++) { 
346
  for (i=0 ; i<height ; i++) { 
347
  /* Build the scanline */
347
  /* Build the scanline */
348
    pscanline = scanline;
348
    pscanline = scanline;
349
    for ( j=0 ; j<width ; j++) {
349
    for ( j=0 ; j<width ; j++) {
350
      col = gp(d, i, j);
350
      col = gp(d, i, j);
351
      *pscanline++ = GETRED(col) ;
351
      *pscanline++ = GETRED(col) ;
352
      *pscanline++ = GETGREEN(col) ;
352
      *pscanline++ = GETGREEN(col) ;
353
      *pscanline++ = GETBLUE(col) ;
353
      *pscanline++ = GETBLUE(col) ;
354
    }
354
    }
355
    jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &scanline, 1);
355
    jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &scanline, 1);
356
  } 
356
  } 
357
 
357
 
358
  /* Step 6: Finish compression */
358
  /* Step 6: Finish compression */
359
 
359
 
360
  jpeg_finish_compress(&cinfo);
360
  jpeg_finish_compress(&cinfo);
361
 
361
 
362
  /* Step 7: release JPEG compression object */
362
  /* Step 7: release JPEG compression object */
363
 
363
 
364
  /* This is an important step since it will release a good deal of memory. */
364
  /* This is an important step since it will release a good deal of memory. */
365
  free(scanline);
365
  free(scanline);
366
  jpeg_destroy_compress(&cinfo);
366
  jpeg_destroy_compress(&cinfo);
367
 
367
 
368
 
368
 
369
  /* And we're done! */
369
  /* And we're done! */
370
  return 1;
370
  return 1;
371
}
371
}
372
 
372
 
373
#endif /* HAVE_JPEG */
373
#endif /* HAVE_JPEG */
374
 
374
 
375
/* 
375
/* 
376
 * Try to save the content of the device 'd' in 'filename' as Windows BMP.
376
 * Try to save the content of the device 'd' in 'filename' as Windows BMP.
377
 * If numbers of colors is less than 256 we use a 'palette' BMP.
377
 * If numbers of colors is less than 256 we use a 'palette' BMP.
378
 * Return 1 on success, 0 on failure 
378
 * Return 1 on success, 0 on failure 
379
*/
379
*/
380
 
380
 
381
#define BMPERROR {R_ShowMessage("Problems writing to 'bmp' file");return 0;} 
381
#define BMPERROR {R_ShowMessage("Problems writing to 'bmp' file");return 0;} 
382
#define BMPW(a) {wrd=a;if(fwrite(&wrd,sizeof(unsigned short),1,fp)!=1) BMPERROR}
382
#define BMPW(a) {wrd=a;if(fwrite(&wrd,sizeof(unsigned short),1,fp)!=1) BMPERROR}
383
#define BMPDW(a) {dwrd=a;if(fwrite(&dwrd,sizeof(unsigned long),1,fp)!=1) BMPERROR}
383
#define BMPDW(a) {dwrd=a;if(fwrite(&dwrd,sizeof(unsigned long),1,fp)!=1) BMPERROR}
384
#define BMPLONG(a) {lng=a;if(fwrite(&lng,sizeof(long),1,fp)!=1) BMPERROR}
384
#define BMPLONG(a) {lng=a;if(fwrite(&lng,sizeof(long),1,fp)!=1) BMPERROR}
385
#define BMPPUTC(a) if(fputc(a,fp)==EOF) BMPERROR;
385
#define BMPPUTC(a) if(fputc(a,fp)==EOF) BMPERROR;
386
#define HEADERSIZE 54
386
#define HEADERSIZE 54
387
 
387
 
388
int R_SaveAsBmp(void  *d, int width, int height, 
388
int R_SaveAsBmp(void  *d, int width, int height, 
389
		unsigned long (*gp)(void *, int, int), int bgr, FILE *fp,
389
		unsigned long (*gp)(void *, int, int), int bgr, FILE *fp,
390
		int res) 
390
		int res) 
391
{
391
{
392
  unsigned long  col, palette[256];
392
  unsigned long  col, palette[256];
393
  int i, j, r, ncols, mid, high, low, withpalette;
393
  int i, j, r, ncols, mid, high, low, withpalette;
394
  int bfOffBits, bfSize, biBitCount, biClrUsed , pad;
394
  int bfOffBits, bfSize, biBitCount, biClrUsed , pad;
395
  unsigned short wrd;
395
  unsigned short wrd;
396
  unsigned long dwrd;
396
  unsigned long dwrd;
397
  long lng, lres;
397
  long lng, lres;
398
  DECLARESHIFTS;
398
  DECLARESHIFTS;
399
 
399
 
400
  /* Have we less than 256 different colors? */
400
  /* Have we less than 256 different colors? */
401
  ncols = mid = 0;
401
  ncols = mid = 0;
402
  withpalette = 1;
402
  withpalette = 1;
403
  for (i=0; i<256 ; i++) palette[i] = 0;
403
  for (i=0; i<256 ; i++) palette[i] = 0;
404
  for (i = 0; (i < height) && withpalette ; i++) {
404
  for (i = 0; (i < height) && withpalette ; i++) {
405
    for (j = 0; (j < width) && withpalette ; j++) {
405
    for (j = 0; (j < width) && withpalette ; j++) {
406
      col = gp(d,i,j) & 0xFFFFFFUL ;
406
      col = gp(d,i,j) & 0xFFFFFFUL ;
407
      /* binary search the palette: */
407
      /* binary search the palette: */
408
      low = 0;  
408
      low = 0;  
409
      high = ncols - 1;
409
      high = ncols - 1;
410
      while (low <= high) {
410
      while (low <= high) {
411
	mid = (low + high)/2;
411
	mid = (low + high)/2;
412
	if ( col < palette[mid] ) high = mid - 1;
412
	if ( col < palette[mid] ) high = mid - 1;
413
	else if ( col > palette[mid] ) low  = mid + 1;
413
	else if ( col > palette[mid] ) low  = mid + 1;
414
	else break;
414
	else break;
415
      }
415
      }
416
      if (high < low) {
416
      if (high < low) {
417
	/* didn't find colour in palette, insert it: */
417
	/* didn't find colour in palette, insert it: */
418
	if (ncols >= 256) {
418
	if (ncols >= 256) {
419
	  withpalette = 0;
419
	  withpalette = 0;
420
	} else {
420
	} else {
421
	  for (r = ncols; r > low; r--)
421
	  for (r = ncols; r > low; r--)
422
	    palette[r] = palette[r-1] ;
422
	    palette[r] = palette[r-1] ;
423
	  palette[low] = col;
423
	  palette[low] = col;
424
	  ncols ++;
424
	  ncols ++;
425
	}
425
	}
426
      }
426
      }
427
    }
427
    }
428
  }
428
  }
429
  /* Compute some part of the header */
429
  /* Compute some part of the header */
430
  if (withpalette) {
430
  if (withpalette) {
431
    bfOffBits = HEADERSIZE + 4 * 256; 
431
    bfOffBits = HEADERSIZE + 4 * 256; 
432
    bfSize = bfOffBits + width * height ;
432
    bfSize = bfOffBits + width * height ;
433
    biBitCount = 8;
433
    biBitCount = 8;
434
    biClrUsed = 256;
434
    biClrUsed = 256;
435
  } else {
435
  } else {
436
    bfOffBits = HEADERSIZE + 4;
436
    bfOffBits = HEADERSIZE + 4;
437
    bfSize = bfOffBits + 3 * width * height ;
437
    bfSize = bfOffBits + 3 * width * height ;
438
    biBitCount = 24;
438
    biBitCount = 24;
439
    biClrUsed = 0;
439
    biClrUsed = 0;
440
  }
440
  }
441
 
441
 
442
  /* write the header */
442
  /* write the header */
443
  BMPW(0x4D42); /* bfType must be "BM" */
443
  BMPW(0x4D42); /* bfType must be "BM" */
444
  BMPDW(bfSize); /*bfSize*/ 
444
  BMPDW(bfSize); /*bfSize*/ 
445
  BMPW(0);BMPW(0); /* bfReserved1 and bfReserved2 must be 0*/
445
  BMPW(0);BMPW(0); /* bfReserved1 and bfReserved2 must be 0*/
446
  BMPDW(bfOffBits); /* bfOffBits */
446
  BMPDW(bfOffBits); /* bfOffBits */
447
  BMPDW(40);	/* biSize */
447
  BMPDW(40);	/* biSize */
448
  BMPLONG(width); /* biWidth */
448
  BMPLONG(width); /* biWidth */
449
  BMPLONG(height); /* biHeight */
449
  BMPLONG(height); /* biHeight */
450
  BMPW(1);	/* biPlanes - must be 1 */
450
  BMPW(1);	/* biPlanes - must be 1 */
451
  BMPW(biBitCount); /* biBitCount */
451
  BMPW(biBitCount); /* biBitCount */
452
  BMPDW(0); /* biCompression=BI_RGB */
452
  BMPDW(0); /* biCompression=BI_RGB */
453
  BMPDW(0); /* biSizeImage (with BI_RGB not needed)*/
453
  BMPDW(0); /* biSizeImage (with BI_RGB not needed)*/
454
  lres = (long)(0.5 + res/0.0254);
454
  lres = (long)(0.5 + res/0.0254);
455
  Rprintf("%d %d %x\n", res, lres, lres);
-
 
456
  BMPLONG(lres); /* XPels/M <- used only by Windows?*/
455
  BMPLONG(lres); /* XPels/M <- used only by Windows?*/
457
  BMPLONG(lres); /* XPels/M */
456
  BMPLONG(lres); /* XPels/M */
458
  BMPDW(biClrUsed); /* biClrUsed */
457
  BMPDW(biClrUsed); /* biClrUsed */
459
  BMPDW(0) ; /* biClrImportant All colours are important */
458
  BMPDW(0) ; /* biClrImportant All colours are important */
460
 
459
 
461
  /* and now the image */
460
  /* and now the image */
462
  if (withpalette) {
461
  if (withpalette) {
463
    /* 8 bit image; write the palette */
462
    /* 8 bit image; write the palette */
464
    for ( i=0; i<256; i++) {
463
    for ( i=0; i<256; i++) {
465
      col = palette[i];
464
      col = palette[i];
466
      BMPPUTC(GETBLUE(col));
465
      BMPPUTC(GETBLUE(col));
467
      BMPPUTC(GETGREEN(col));
466
      BMPPUTC(GETGREEN(col));
468
      BMPPUTC(GETRED(col));
467
      BMPPUTC(GETRED(col));
469
      BMPPUTC(0);
468
      BMPPUTC(0);
470
    }
469
    }
471
    /* Rows must be padded to 4-byte boundary */
470
    /* Rows must be padded to 4-byte boundary */
472
    for ( pad=0 ; ((width+pad) & 3) != 0; pad++);
471
    for ( pad=0 ; ((width+pad) & 3) != 0; pad++);
473
    /* and then the pixels */
472
    /* and then the pixels */
474
    for (i=height-1 ; i>=0 ; i--) { 
473
    for (i=height-1 ; i>=0 ; i--) { 
475
      for ( j=0 ; j<width ; j++) {
474
      for ( j=0 ; j<width ; j++) {
476
	col = gp(d, i, j)&0xFFFFFFUL;
475
	col = gp(d, i, j)&0xFFFFFFUL;
477
	/* binary search the palette (the colour must be there): */
476
	/* binary search the palette (the colour must be there): */
478
	low = 0;  high = ncols - 1;
477
	low = 0;  high = ncols - 1;
479
	while (low <= high) {
478
	while (low <= high) {
480
	  mid = (low + high)/2;
479
	  mid = (low + high)/2;
481
	  if      (col < palette[mid]) high = mid - 1;
480
	  if      (col < palette[mid]) high = mid - 1;
482
	  else if (col > palette[mid]) low  = mid + 1;
481
	  else if (col > palette[mid]) low  = mid + 1;
483
	  else break;
482
	  else break;
484
	}
483
	}
485
	BMPPUTC(mid);
484
	BMPPUTC(mid);
486
      }
485
      }
487
      for (j=0; j<pad; j++) BMPPUTC(0);
486
      for (j=0; j<pad; j++) BMPPUTC(0);
488
    }
487
    }
489
  } else {
488
  } else {
490
    /* 24 bits image */
489
    /* 24 bits image */
491
    BMPDW(0); /* null bmiColors */
490
    BMPDW(0); /* null bmiColors */
492
    for ( pad=0 ; ((3*width+pad) & 3) != 0; pad++); /*padding*/    
491
    for ( pad=0 ; ((3*width+pad) & 3) != 0; pad++); /*padding*/    
493
    for (i=height-1 ; i>=0 ; i--) { 
492
    for (i=height-1 ; i>=0 ; i--) { 
494
      for ( j=0 ; j<width ; j++) {
493
      for ( j=0 ; j<width ; j++) {
495
	col = gp(d, i, j)&0xFFFFFFUL;
494
	col = gp(d, i, j)&0xFFFFFFUL;
496
	BMPPUTC(GETBLUE(col));
495
	BMPPUTC(GETBLUE(col));
497
	BMPPUTC(GETGREEN(col));
496
	BMPPUTC(GETGREEN(col));
498
	BMPPUTC(GETRED(col));
497
	BMPPUTC(GETRED(col));
499
      }
498
      }
500
      for (j=0; j<pad; j++) BMPPUTC(0);
499
      for (j=0; j<pad; j++) BMPPUTC(0);
501
    }
500
    }
502
  }
501
  }
503
  return 1;
502
  return 1;
504
}
503
}
505
 
504
 
506
 
505
 
507
 
506
 
508
 
507
 
509
 
508
 
510
 
509
 
511
 
510
 
512
 
511