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