The R Project SVN R

Rev

Details | Last modification | View Log | RSS feed

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