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