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