source: liacs/MIR2010/SourceCode/cximage/ximatif.cpp@ 181

Last change on this file since 181 was 95, checked in by Rick van der Zwet, 15 years ago

Bad boy, improper move of directory

File size: 29.8 KB
Line 
1/*
2 * File: ximatif.cpp
3 * Purpose: Platform Independent TIFF Image Class Loader and Writer
4 * 07/Aug/2001 Davide Pizzolato - www.xdp.it
5 * CxImage version 6.0.0 02/Feb/2008
6 */
7
8#include "ximatif.h"
9
10#if CXIMAGE_SUPPORT_TIF
11
12#define FIX_16BPP_DARKIMG // + VK: if uncomment, dark 16bpp images are fixed
13
14#include "tiff/tiffio.h"
15
16#define CVT(x) (((x) * 255L) / ((1L<<16)-1))
17#define SCALE(x) (((x)*((1L<<16)-1))/255)
18#define CalculateLine(width,bitdepth) (((width * bitdepth) + 7) / 8)
19#define CalculatePitch(line) (line + 3 & ~3)
20
21extern "C" TIFF* _TIFFOpenEx(CxFile* stream, const char* mode);
22
23////////////////////////////////////////////////////////////////////////////////
24CxImageTIF::~CxImageTIF()
25{
26 if (m_tif2) TIFFClose(m_tif2);
27}
28////////////////////////////////////////////////////////////////////////////////
29#if CXIMAGE_SUPPORT_DECODE
30////////////////////////////////////////////////////////////////////////////////
31bool CxImageTIF::Decode(CxFile * hFile)
32{
33 //Comment this line if you need more information on errors
34 // TIFFSetErrorHandler(NULL); //<Patrick Hoffmann>
35
36 //Open file and fill the TIFF structure
37 // m_tif = TIFFOpen(imageFileName,"rb");
38 TIFF* m_tif = _TIFFOpenEx(hFile, "rb");
39
40 uint32 height=0;
41 uint32 width=0;
42 uint16 bitspersample=1;
43 uint16 samplesperpixel=1;
44 uint32 rowsperstrip=(DWORD)-1;
45 uint16 photometric=0;
46 uint16 compression=1;
47 uint16 orientation=ORIENTATION_TOPLEFT; //<vho>
48 uint16 res_unit; //<Trifon>
49 uint32 x, y;
50 float resolution, offset;
51 BOOL isRGB;
52 BYTE *bits; //pointer to source data
53 BYTE *bits2; //pointer to destination data
54
55 cx_try
56 {
57 //check if it's a tiff file
58 if (!m_tif)
59 cx_throw("Error encountered while opening TIFF file");
60
61 // <Robert Abram> - 12/2002 : get NumFrames directly, instead of looping
62 // info.nNumFrames=0;
63 // while(TIFFSetDirectory(m_tif,(uint16)info.nNumFrames)) info.nNumFrames++;
64 info.nNumFrames = TIFFNumberOfDirectories(m_tif);
65
66 if (!TIFFSetDirectory(m_tif, (uint16)info.nFrame))
67 cx_throw("Error: page not present in TIFF file");
68
69 //get image info
70 TIFFGetField(m_tif, TIFFTAG_IMAGEWIDTH, &width);
71 TIFFGetField(m_tif, TIFFTAG_IMAGELENGTH, &height);
72 TIFFGetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
73 TIFFGetField(m_tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
74 TIFFGetField(m_tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
75 TIFFGetField(m_tif, TIFFTAG_PHOTOMETRIC, &photometric);
76 TIFFGetField(m_tif, TIFFTAG_ORIENTATION, &orientation);
77
78 if (info.nEscape == -1) {
79 // Return output dimensions only
80 head.biWidth = width;
81 head.biHeight = height;
82 info.dwType = CXIMAGE_FORMAT_TIF;
83 cx_throw("output dimensions returned");
84 }
85
86 TIFFGetFieldDefaulted(m_tif, TIFFTAG_RESOLUTIONUNIT, &res_unit);
87 if (TIFFGetField(m_tif, TIFFTAG_XRESOLUTION, &resolution))
88 {
89 if (res_unit == RESUNIT_CENTIMETER) resolution = (float)(resolution*2.54f + 0.5f);
90 SetXDPI((long)resolution);
91 }
92 if (TIFFGetField(m_tif, TIFFTAG_YRESOLUTION, &resolution))
93 {
94 if (res_unit == RESUNIT_CENTIMETER) resolution = (float)(resolution*2.54f + 0.5f);
95 SetYDPI((long)resolution);
96 }
97
98 if (TIFFGetField(m_tif, TIFFTAG_XPOSITION, &offset)) info.xOffset = (long)offset;
99 if (TIFFGetField(m_tif, TIFFTAG_YPOSITION, &offset)) info.yOffset = (long)offset;
100
101 head.biClrUsed=0;
102 info.nBkgndIndex =-1;
103
104 if (rowsperstrip>height){
105 rowsperstrip=height;
106 TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
107 }
108
109 isRGB = /*(bitspersample >= 8) && (VK: it is possible so for RGB to have < 8 bpp!)*/
110 (photometric == PHOTOMETRIC_RGB) ||
111 (photometric == PHOTOMETRIC_YCBCR) ||
112 (photometric == PHOTOMETRIC_SEPARATED) ||
113 (photometric == PHOTOMETRIC_LOGL) ||
114 (photometric == PHOTOMETRIC_LOGLUV);
115
116 if (isRGB){
117 head.biBitCount=24;
118 }else{
119 if ((photometric==PHOTOMETRIC_MINISBLACK)||(photometric==PHOTOMETRIC_MINISWHITE)||(photometric==PHOTOMETRIC_PALETTE)){
120 if (bitspersample == 1){
121 head.biBitCount=1; //B&W image
122 head.biClrUsed =2;
123 } else if (bitspersample == 4) {
124 head.biBitCount=4; //16 colors gray scale
125 head.biClrUsed =16;
126 } else {
127 head.biBitCount=8; //gray scale
128 head.biClrUsed =256;
129 }
130 } else if (bitspersample == 4) {
131 head.biBitCount=4; // 16 colors
132 head.biClrUsed=16;
133 } else {
134 head.biBitCount=8; //256 colors
135 head.biClrUsed=256;
136 }
137
138 if ((bitspersample > 8) && (photometric==PHOTOMETRIC_PALETTE)) // + VK + (BIG palette! => convert to RGB)
139 { head.biBitCount=24;
140 head.biClrUsed =0;
141 }
142 }
143
144 if (info.nEscape) cx_throw("Cancelled"); // <vho> - cancel decoding
145
146 Create(width,height,head.biBitCount,CXIMAGE_FORMAT_TIF); //image creation
147 if (!pDib) cx_throw("CxImageTIF can't create image");
148
149#if CXIMAGE_SUPPORT_ALPHA
150 if (samplesperpixel==4) AlphaCreate(); //add alpha support for 32bpp tiffs
151 if (samplesperpixel==2 && bitspersample==8) AlphaCreate(); //add alpha support for 8bpp + alpha
152#endif //CXIMAGE_SUPPORT_ALPHA
153
154 TIFFGetField(m_tif, TIFFTAG_COMPRESSION, &compression);
155 SetCodecOption(compression); // <DPR> save original compression type
156
157 if (isRGB) {
158 // Read the whole image into one big RGBA buffer using
159 // the traditional TIFFReadRGBAImage() API that we trust.
160 uint32* raster; // retrieve RGBA image
161 uint32 *row;
162
163 raster = (uint32*)_TIFFmalloc(width * height * sizeof (uint32));
164 if (raster == NULL) cx_throw("No space for raster buffer");
165
166 // Read the image in one chunk into an RGBA array
167 if(!TIFFReadRGBAImage(m_tif, width, height, raster, 1)) {
168 _TIFFfree(raster);
169 cx_throw("Corrupted TIFF file!");
170 }
171
172 // read the raster lines and save them in the DIB
173 // with RGB mode, we have to change the order of the 3 samples RGB
174 row = &raster[0];
175 bits2 = info.pImage;
176 for (y = 0; y < height; y++) {
177
178 if (info.nEscape){ // <vho> - cancel decoding
179 _TIFFfree(raster);
180 cx_throw("Cancelled");
181 }
182
183 bits = bits2;
184 for (x = 0; x < width; x++) {
185 *bits++ = (BYTE)TIFFGetB(row[x]);
186 *bits++ = (BYTE)TIFFGetG(row[x]);
187 *bits++ = (BYTE)TIFFGetR(row[x]);
188#if CXIMAGE_SUPPORT_ALPHA
189 if (samplesperpixel==4) AlphaSet(x,y,(BYTE)TIFFGetA(row[x]));
190#endif //CXIMAGE_SUPPORT_ALPHA
191 }
192 row += width;
193 bits2 += info.dwEffWidth;
194 }
195 _TIFFfree(raster);
196 } else {
197 int BIG_palette = (bitspersample > 8) && // + VK
198 (photometric==PHOTOMETRIC_PALETTE);
199 if (BIG_palette && (bitspersample > 24)) // + VK
200 cx_throw("Too big palette to handle"); // + VK
201
202 RGBQUAD *pal;
203 pal=(RGBQUAD*)calloc(BIG_palette ? 1<<bitspersample : 256,sizeof(RGBQUAD));
204 // ! VK: it coasts nothing but more correct to use 256 as temp palette storage
205 // ! VK: but for case of BIG palette it just copied
206 if (pal==NULL) cx_throw("Unable to allocate TIFF palette");
207
208 int bpp = bitspersample <= 8 ? bitspersample : 8; // + VK (to use instead of bitspersample for case of > 8)
209
210 // set up the colormap based on photometric
211 switch(photometric) {
212 case PHOTOMETRIC_MINISBLACK: // bitmap and greyscale image types
213 case PHOTOMETRIC_MINISWHITE:
214 if (bitspersample == 1) { // Monochrome image
215 if (photometric == PHOTOMETRIC_MINISBLACK) {
216 pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;
217 } else {
218 pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 255;
219 }
220 } else { // need to build the scale for greyscale images
221 if (photometric == PHOTOMETRIC_MINISBLACK) {
222 for (int i=0; i<(1<<bpp); i++){
223 pal[i].rgbRed = pal[i].rgbGreen = pal[i].rgbBlue = (BYTE)(i*(255/((1<<bpp)-1)));
224 }
225 } else {
226 for (int i=0; i<(1<<bpp); i++){
227 pal[i].rgbRed = pal[i].rgbGreen = pal[i].rgbBlue = (BYTE)(255-i*(255/((1<<bpp)-1)));
228 }
229 }
230 }
231 break;
232 case PHOTOMETRIC_PALETTE: // color map indexed
233 uint16 *red;
234 uint16 *green;
235 uint16 *blue;
236 TIFFGetField(m_tif, TIFFTAG_COLORMAP, &red, &green, &blue);
237
238 // Is the palette 16 or 8 bits ?
239 BOOL Palette16Bits = /*FALSE*/ BIG_palette;
240 if (!BIG_palette) {
241 int n= 1<<bpp;
242 while (n-- > 0) {
243 if (red[n] >= 256 || green[n] >= 256 || blue[n] >= 256) {
244 Palette16Bits=TRUE;
245 break;
246 }
247 }
248 }
249
250 // load the palette in the DIB
251 for (int i = (1 << ( BIG_palette ? bitspersample : bpp )) - 1; i >= 0; i--) {
252 if (Palette16Bits) {
253 pal[i].rgbRed =(BYTE) CVT(red[i]);
254 pal[i].rgbGreen = (BYTE) CVT(green[i]);
255 pal[i].rgbBlue = (BYTE) CVT(blue[i]);
256 } else {
257 pal[i].rgbRed = (BYTE) red[i];
258 pal[i].rgbGreen = (BYTE) green[i];
259 pal[i].rgbBlue = (BYTE) blue[i];
260 }
261 }
262 break;
263 }
264 if (!BIG_palette) { // + VK (BIG palette is stored until image is ready)
265 SetPalette(pal,/*head.biClrUsed*/ 1<<bpp); //palette assign // * VK
266 free(pal);
267 pal = NULL;
268 }
269
270 // read the tiff lines and save them in the DIB
271 uint32 nrow;
272 uint32 ys;
273 int line = CalculateLine(width, bitspersample * samplesperpixel);
274
275 /*long bitsize = TIFFStripSize(m_tif);
276 //verify bitsize: could be wrong if StripByteCounts is missing.
277 if (bitsize<(long)(head.biSizeImage*samplesperpixel))
278 bitsize = head.biSizeImage*samplesperpixel;*/
279
280 // BT: patch found on http://www.xdp.it/cgi-bin/yabb/YaBB.pl?board=cximage_bugs;action=print;num=1112094205
281 /*long bitsize= TIFFStripSize(m_tif);
282 //verify bitsize: could be wrong if StripByteCounts is missing.
283 if (bitsize>(long)(head.biSizeImage*samplesperpixel)) bitsize=head.biSizeImage*samplesperpixel;*/
284 long bitsize = head.biSizeImage*samplesperpixel;
285
286 if ((bitspersample > 8) && (bitspersample != 16)) // + VK (for bitspersample == 9..15,17..32..64
287 bitsize *= (bitspersample + 7)/8;
288
289 int tiled_image = TIFFIsTiled(m_tif);
290 uint32 tw=0, tl=0;
291 BYTE* tilebuf=NULL;
292 if (tiled_image){
293 TIFFGetField(m_tif, TIFFTAG_TILEWIDTH, &tw);
294 TIFFGetField(m_tif, TIFFTAG_TILELENGTH, &tl);
295 rowsperstrip = tl;
296 bitsize = TIFFTileSize(m_tif) * (int)(1+width/tw);
297 tilebuf = (BYTE*)malloc(TIFFTileSize(m_tif));
298 }
299
300 bits = (BYTE*)malloc(bitspersample==16? bitsize*2 : bitsize); // * VK
301 BYTE * bits16 = NULL; // + VK
302 int line16 = 0; // + VK
303
304 if (!tiled_image && bitspersample==16) { // + VK +
305 line16 = line;
306 line = CalculateLine(width, 8 * samplesperpixel);
307 bits16 = bits;
308 bits = (BYTE*)malloc(bitsize);
309 }
310
311 if (bits==NULL){
312 if (bits16) free(bits16); // + VK
313 if (pal) free(pal); // + VK
314 if (tilebuf)free(tilebuf); // + VK
315 cx_throw("CxImageTIF can't allocate memory");
316 }
317
318#ifdef FIX_16BPP_DARKIMG // + VK: for each line, store shift count bits used to fix it
319 BYTE* row_shifts = NULL;
320 if (bits16) row_shifts = (BYTE*)malloc(height);
321#endif
322
323 for (ys = 0; ys < height; ys += rowsperstrip) {
324
325 if (info.nEscape){ // <vho> - cancel decoding
326 free(bits);
327 cx_throw("Cancelled");
328 }
329
330 nrow = (ys + rowsperstrip > height ? height - ys : rowsperstrip);
331
332 if (tiled_image){
333 uint32 imagew = TIFFScanlineSize(m_tif);
334 uint32 tilew = TIFFTileRowSize(m_tif);
335 int iskew = imagew - tilew;
336 uint8* bufp = (uint8*) bits;
337
338 uint32 colb = 0;
339 for (uint32 col = 0; col < width; col += tw) {
340 if (TIFFReadTile(m_tif, tilebuf, col, ys, 0, 0) < 0){
341 free(tilebuf);
342 free(bits);
343 cx_throw("Corrupted tiled TIFF file!");
344 }
345
346 if (colb + tw > imagew) {
347 uint32 owidth = imagew - colb;
348 uint32 oskew = tilew - owidth;
349 TileToStrip(bufp + colb, tilebuf, nrow, owidth, oskew + iskew, oskew );
350 } else {
351 TileToStrip(bufp + colb, tilebuf, nrow, tilew, iskew, 0);
352 }
353 colb += tilew;
354 }
355
356 } else {
357 if (TIFFReadEncodedStrip(m_tif, TIFFComputeStrip(m_tif, ys, 0),
358 (bits16? bits16 : bits), nrow * (bits16 ? line16 : line)) == -1) { // * VK
359
360#ifdef NOT_IGNORE_CORRUPTED
361 free(bits);
362 if (bits16) free(bits16); // + VK
363 cx_throw("Corrupted TIFF file!");
364#else
365 break;
366#endif
367 }
368 }
369
370 for (y = 0; y < nrow; y++) {
371 long offset=(nrow-y-1)*line;
372 if ((bitspersample==16) && !BIG_palette) { // * VK
373 long offset16 = (nrow-y-1)*line16; // + VK
374 if (bits16) { // + VK +
375#ifdef FIX_16BPP_DARKIMG
376 int the_shift;
377 BYTE hi_byte, hi_max=0;
378 DWORD xi;
379 for (xi=0;xi<(uint32)line;xi++) {
380 hi_byte = bits16[xi*2+offset16+1];
381 if(hi_byte>hi_max)
382 hi_max = hi_byte;
383 }
384 the_shift = (hi_max == 0) ? 8 : 0;
385 if (!the_shift)
386 while( ! (hi_max & 0x80) ) {
387 the_shift++;
388 hi_max <<= 1;
389 }
390 row_shifts[height-ys-nrow+y] = the_shift;
391 the_shift = 8 - the_shift;
392 for (xi=0;xi<(uint32)line;xi++)
393 bits[xi+offset]= ((bits16[xi*2+offset16+1]<<8) | bits16[xi*2+offset16]) >> the_shift;
394#else
395 for (DWORD xi=0;xi<(uint32)line;xi++)
396 bits[xi+offset]=bits16[xi*2+offset16+1];
397#endif
398 } else {
399 for (DWORD xi=0;xi<width;xi++)
400 bits[xi+offset]=bits[xi*2+offset+1];
401 }
402 }
403 if (samplesperpixel==1) {
404 if (BIG_palette)
405 if (bits16) {
406 long offset16 = (nrow-y-1)*line16; // + VK
407 MoveBitsPal( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
408 bits16 + offset16, width, bitspersample, pal );
409 } else
410 MoveBitsPal( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
411 bits + offset, width, bitspersample, pal );
412 else if ((bitspersample == head.biBitCount) ||
413 (bitspersample == 16)) //simple 8bpp, 4bpp image or 16bpp
414 memcpy(info.pImage+info.dwEffWidth*(height-ys-nrow+y),bits+offset,info.dwEffWidth);
415 else
416 MoveBits( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
417 bits + offset, width, bitspersample );
418 } else if (samplesperpixel==2) { //8bpp image with alpha layer
419 int xi=0;
420 int ii=0;
421 int yi=height-ys-nrow+y;
422#if CXIMAGE_SUPPORT_ALPHA
423 if (!pAlpha) AlphaCreate(); // + VK
424#endif //CXIMAGE_SUPPORT_ALPHA
425 while (ii<line){
426 SetPixelIndex(xi,yi,bits[ii+offset]);
427#if CXIMAGE_SUPPORT_ALPHA
428 AlphaSet(xi,yi,bits[ii+offset+1]);
429#endif //CXIMAGE_SUPPORT_ALPHA
430 ii+=2;
431 xi++;
432 if (xi>=(int)width){
433 yi--;
434 xi=0;
435 }
436 }
437 } else { //photometric==PHOTOMETRIC_CIELAB
438 if (head.biBitCount!=24){ //fix image
439 Create(width,height,24,CXIMAGE_FORMAT_TIF);
440#if CXIMAGE_SUPPORT_ALPHA
441 if (samplesperpixel==4) AlphaCreate();
442#endif //CXIMAGE_SUPPORT_ALPHA
443 }
444
445 int xi=0;
446 uint32 ii=0;
447 int yi=height-ys-nrow+y;
448 RGBQUAD c;
449 int l,a,b,bitsoffset;
450 double p,cx,cy,cz,cr,cg,cb;
451 while (ii</*line*/width){ // * VK
452 bitsoffset = ii*samplesperpixel+offset;
453 l=bits[bitsoffset];
454 a=bits[bitsoffset+1];
455 b=bits[bitsoffset+2];
456 if (a>127) a-=256;
457 if (b>127) b-=256;
458 // lab to xyz
459 p = (l/2.55 + 16) / 116.0;
460 cx = pow( p + a * 0.002, 3);
461 cy = pow( p, 3);
462 cz = pow( p - b * 0.005, 3);
463 // white point
464 cx*=0.95047;
465 //cy*=1.000;
466 cz*=1.0883;
467 // xyz to rgb
468 cr = 3.240479 * cx - 1.537150 * cy - 0.498535 * cz;
469 cg = -0.969256 * cx + 1.875992 * cy + 0.041556 * cz;
470 cb = 0.055648 * cx - 0.204043 * cy + 1.057311 * cz;
471
472 if ( cr > 0.00304 ) cr = 1.055 * pow(cr,0.41667) - 0.055;
473 else cr = 12.92 * cr;
474 if ( cg > 0.00304 ) cg = 1.055 * pow(cg,0.41667) - 0.055;
475 else cg = 12.92 * cg;
476 if ( cb > 0.00304 ) cb = 1.055 * pow(cb,0.41667) - 0.055;
477 else cb = 12.92 * cb;
478
479 c.rgbRed =(BYTE)max(0,min(255,(int)(cr*255)));
480 c.rgbGreen=(BYTE)max(0,min(255,(int)(cg*255)));
481 c.rgbBlue =(BYTE)max(0,min(255,(int)(cb*255)));
482
483 SetPixelColor(xi,yi,c);
484#if CXIMAGE_SUPPORT_ALPHA
485 if (samplesperpixel==4) AlphaSet(xi,yi,bits[bitsoffset+3]);
486#endif //CXIMAGE_SUPPORT_ALPHA
487 ii++;
488 xi++;
489 if (xi>=(int)width){
490 yi--;
491 xi=0;
492 }
493 }
494 }
495 }
496 }
497 free(bits);
498 if (bits16) free(bits16);
499
500#ifdef FIX_16BPP_DARKIMG
501 if (row_shifts && (samplesperpixel == 1) && (bitspersample==16) && !BIG_palette) {
502 // 1. calculate maximum necessary shift
503 int min_row_shift = 8;
504 for( y=0; y<height; y++ ) {
505 if (min_row_shift > row_shifts[y]) min_row_shift = row_shifts[y];
506 }
507 // 2. for rows having less shift value, correct such rows:
508 for( y=0; y<height; y++ ) {
509 if (min_row_shift < row_shifts[y]) {
510 int need_shift = row_shifts[y] - min_row_shift;
511 BYTE* data = info.pImage + info.dwEffWidth * y;
512 for( x=0; x<width; x++, data++ )
513 *data >>= need_shift;
514 }
515 }
516 }
517 if (row_shifts) free( row_shifts );
518#endif
519
520 if (tiled_image) free(tilebuf);
521 if (pal) free(pal);
522
523 switch(orientation){
524 case ORIENTATION_TOPRIGHT: /* row 0 top, col 0 rhs */
525 Mirror();
526 break;
527 case ORIENTATION_BOTRIGHT: /* row 0 bottom, col 0 rhs */
528 Flip();
529 Mirror();
530 break;
531 case ORIENTATION_BOTLEFT: /* row 0 bottom, col 0 lhs */
532 Flip();
533 break;
534 case ORIENTATION_LEFTTOP: /* row 0 lhs, col 0 top */
535 RotateRight();
536 Mirror();
537 break;
538 case ORIENTATION_RIGHTTOP: /* row 0 rhs, col 0 top */
539 RotateLeft();
540 break;
541 case ORIENTATION_RIGHTBOT: /* row 0 rhs, col 0 bottom */
542 RotateLeft();
543 Mirror();
544 break;
545 case ORIENTATION_LEFTBOT: /* row 0 lhs, col 0 bottom */
546 RotateRight();
547 break;
548 }
549
550 }
551 } cx_catch {
552 if (strcmp(message,"")) strncpy(info.szLastError,message,255);
553 if (m_tif) TIFFClose(m_tif);
554 if (info.nEscape == -1 && info.dwType == CXIMAGE_FORMAT_TIF) return true;
555 return false;
556 }
557 TIFFClose(m_tif);
558 return true;
559}
560////////////////////////////////////////////////////////////////////////////////
561#endif //CXIMAGE_SUPPORT_DECODE
562////////////////////////////////////////////////////////////////////////////////
563#if CXIMAGE_SUPPORT_ENCODE
564////////////////////////////////////////////////////////////////////////////////
565bool CxImageTIF::Encode(CxFile * hFile, bool bAppend)
566{
567 cx_try
568 {
569 if (hFile==NULL) cx_throw(CXIMAGE_ERR_NOFILE);
570 if (pDib==NULL) cx_throw(CXIMAGE_ERR_NOIMAGE);
571
572 // <RJ> replaced "w+b" with "a", to append an image directly on an existing file
573 if (m_tif2==NULL) m_tif2=_TIFFOpenEx(hFile, "a");
574 if (m_tif2==NULL) cx_throw("initialization fail");
575
576 if (bAppend || m_pages) m_multipage=true;
577 m_pages++;
578
579 if (!EncodeBody(m_tif2,m_multipage,m_pages,m_pages)) cx_throw("Error saving TIFF file");
580 if (bAppend) {
581 if (!TIFFWriteDirectory(m_tif2)) cx_throw("Error saving TIFF directory");
582 }
583 } cx_catch {
584 if (strcmp(message,"")) strncpy(info.szLastError,message,255);
585 if (m_tif2){
586 TIFFClose(m_tif2);
587 m_tif2=NULL;
588 m_multipage=false;
589 m_pages=0;
590 }
591 return false;
592 }
593 if (!bAppend){
594 TIFFClose(m_tif2);
595 m_tif2=NULL;
596 m_multipage=false;
597 m_pages=0;
598 }
599 return true;
600}
601////////////////////////////////////////////////////////////////////////////////
602// Thanks to Abe <God(dot)bless(at)marihuana(dot)com>
603bool CxImageTIF::Encode(CxFile * hFile, CxImage ** pImages, int pagecount)
604{
605 cx_try
606 {
607 if (hFile==NULL) cx_throw("invalid file pointer");
608 if (pImages==NULL || pagecount<=0) cx_throw("multipage TIFF, no images!");
609
610 int i;
611 for (i=0; i<pagecount; i++){
612 if (pImages[i]==NULL)
613 cx_throw("Bad image pointer");
614 if (!(pImages[i]->IsValid()))
615 cx_throw("Empty image");
616 }
617
618 CxImageTIF ghost;
619 for (i=0; i<pagecount; i++){
620 ghost.Ghost(pImages[i]);
621 if (!ghost.Encode(hFile,true)) cx_throw("Error saving TIFF file");
622 }
623 } cx_catch {
624 if (strcmp(message,"")) strncpy(info.szLastError,message,255);
625 return false;
626 }
627 return true;
628}
629////////////////////////////////////////////////////////////////////////////////
630bool CxImageTIF::EncodeBody(TIFF *m_tif, bool multipage, int page, int pagecount)
631{
632 uint32 height=head.biHeight;
633 uint32 width=head.biWidth;
634 uint16 bitcount=head.biBitCount;
635 uint16 bitspersample;
636 uint16 samplesperpixel;
637 uint16 photometric=0;
638 uint16 compression;
639// uint16 pitch;
640// int line;
641 uint32 x, y;
642
643 samplesperpixel = ((bitcount == 24) || (bitcount == 32)) ? (BYTE)3 : (BYTE)1;
644#if CXIMAGE_SUPPORT_ALPHA
645 if (bitcount==24 && AlphaIsValid()) { bitcount=32; samplesperpixel=4; }
646#endif //CXIMAGE_SUPPORT_ALPHA
647
648 bitspersample = bitcount / samplesperpixel;
649
650 //set the PHOTOMETRIC tag
651 RGBQUAD *rgb = GetPalette();
652 switch (bitcount) {
653 case 1:
654 if (CompareColors(&rgb[0],&rgb[1])<0) {
655 /* <abe> some viewers do not handle PHOTOMETRIC_MINISBLACK:
656 * let's transform the image in PHOTOMETRIC_MINISWHITE
657 */
658 //invert the colors
659 RGBQUAD tempRGB=GetPaletteColor(0);
660 SetPaletteColor(0,GetPaletteColor(1));
661 SetPaletteColor(1,tempRGB);
662 //invert the pixels
663 BYTE *iSrc=info.pImage;
664 for (unsigned long i=0;i<head.biSizeImage;i++){
665 *iSrc=(BYTE)~(*(iSrc));
666 iSrc++;
667 }
668 photometric = PHOTOMETRIC_MINISWHITE;
669 //photometric = PHOTOMETRIC_MINISBLACK;
670 } else {
671 photometric = PHOTOMETRIC_MINISWHITE;
672 }
673 break;
674 case 4: // Check if the DIB has a color or a greyscale palette
675 case 8:
676 photometric = PHOTOMETRIC_MINISBLACK; //default to gray scale
677 for (x = 0; x < head.biClrUsed; x++) {
678 if ((rgb->rgbRed != x)||(rgb->rgbRed != rgb->rgbGreen)||(rgb->rgbRed != rgb->rgbBlue)){
679 photometric = PHOTOMETRIC_PALETTE;
680 break;
681 }
682 rgb++;
683 }
684 break;
685 case 24:
686 case 32:
687 photometric = PHOTOMETRIC_RGB;
688 break;
689 }
690
691#if CXIMAGE_SUPPORT_ALPHA
692 if (AlphaIsValid() && bitcount==8) samplesperpixel=2; //8bpp + alpha layer
693#endif //CXIMAGE_SUPPORT_ALPHA
694
695// line = CalculateLine(width, bitspersample * samplesperpixel);
696// pitch = (uint16)CalculatePitch(line);
697
698 //prepare the palette struct
699 RGBQUAD pal[256];
700 if (GetPalette()){
701 BYTE b;
702 memcpy(pal,GetPalette(),GetPaletteSize());
703 for(WORD a=0;a<head.biClrUsed;a++){ //swap blue and red components
704 b=pal[a].rgbBlue; pal[a].rgbBlue=pal[a].rgbRed; pal[a].rgbRed=b;
705 }
706 }
707
708 // handle standard width/height/bpp stuff
709 TIFFSetField(m_tif, TIFFTAG_IMAGEWIDTH, width);
710 TIFFSetField(m_tif, TIFFTAG_IMAGELENGTH, height);
711 TIFFSetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
712 TIFFSetField(m_tif, TIFFTAG_BITSPERSAMPLE, bitspersample);
713 TIFFSetField(m_tif, TIFFTAG_PHOTOMETRIC, photometric);
714 TIFFSetField(m_tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); // single image plane
715 TIFFSetField(m_tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
716
717 uint32 rowsperstrip = TIFFDefaultStripSize(m_tif, (uint32) -1); //<REC> gives better compression
718 TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
719
720 // handle metrics
721 TIFFSetField(m_tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
722 TIFFSetField(m_tif, TIFFTAG_XRESOLUTION, (float)info.xDPI);
723 TIFFSetField(m_tif, TIFFTAG_YRESOLUTION, (float)info.yDPI);
724// TIFFSetField(m_tif, TIFFTAG_XPOSITION, (float)info.xOffset);
725// TIFFSetField(m_tif, TIFFTAG_YPOSITION, (float)info.yOffset);
726
727 // multi-paging - Thanks to Abe <God(dot)bless(at)marihuana(dot)com>
728 if (multipage)
729 {
730 char page_number[20];
731 sprintf(page_number, "Page %d", page);
732
733 TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
734 TIFFSetField(m_tif, TIFFTAG_PAGENUMBER, page,pagecount);
735 TIFFSetField(m_tif, TIFFTAG_PAGENAME, page_number);
736 } else {
737 TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, 0);
738 }
739
740 // palettes (image colormaps are automatically scaled to 16-bits)
741 if (photometric == PHOTOMETRIC_PALETTE) {
742 uint16 *r, *g, *b;
743 r = (uint16 *) _TIFFmalloc(sizeof(uint16) * 3 * 256);
744 g = r + 256;
745 b = g + 256;
746
747 for (int i = 255; i >= 0; i--) {
748 b[i] = (uint16)SCALE((uint16)pal[i].rgbRed);
749 g[i] = (uint16)SCALE((uint16)pal[i].rgbGreen);
750 r[i] = (uint16)SCALE((uint16)pal[i].rgbBlue);
751 }
752
753 TIFFSetField(m_tif, TIFFTAG_COLORMAP, r, g, b);
754 _TIFFfree(r);
755 }
756
757 // compression
758 if (GetCodecOption(CXIMAGE_FORMAT_TIF)) {
759 compression = (WORD)GetCodecOption(CXIMAGE_FORMAT_TIF);
760 } else {
761 switch (bitcount) {
762 case 1 :
763 compression = COMPRESSION_CCITTFAX4;
764 break;
765 case 4 :
766 case 8 :
767 compression = COMPRESSION_LZW;
768 break;
769 case 24 :
770 case 32 :
771 compression = COMPRESSION_JPEG;
772 break;
773 default :
774 compression = COMPRESSION_NONE;
775 break;
776 }
777 }
778 TIFFSetField(m_tif, TIFFTAG_COMPRESSION, compression);
779
780 switch (compression) {
781 case COMPRESSION_JPEG:
782 TIFFSetField(m_tif, TIFFTAG_JPEGQUALITY, GetJpegQuality());
783 TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, ((7+rowsperstrip)>>3)<<3);
784 break;
785 case COMPRESSION_LZW:
786 if (bitcount>=8) TIFFSetField(m_tif, TIFFTAG_PREDICTOR, 2);
787 break;
788 }
789
790 // read the DIB lines from bottom to top and save them in the TIF
791
792 BYTE *bits;
793 switch(bitcount) {
794 case 1 :
795 case 4 :
796 case 8 :
797 {
798 if (samplesperpixel==1){
799 bits = (BYTE*)malloc(info.dwEffWidth);
800 if (!bits) return false;
801 for (y = 0; y < height; y++) {
802 memcpy(bits,info.pImage + (height - y - 1)*info.dwEffWidth,info.dwEffWidth);
803 if (TIFFWriteScanline(m_tif,bits, y, 0)==-1){
804 free(bits);
805 return false;
806 }
807 }
808 free(bits);
809 }
810#if CXIMAGE_SUPPORT_ALPHA
811 else { //8bpp + alpha layer
812 bits = (BYTE*)malloc(2*width);
813 if (!bits) return false;
814 for (y = 0; y < height; y++) {
815 for (x=0;x<width;x++){
816 bits[2*x]=BlindGetPixelIndex(x,height - y - 1);
817 bits[2*x+1]=AlphaGet(x,height - y - 1);
818 }
819 if (TIFFWriteScanline(m_tif,bits, y, 0)==-1) {
820 free(bits);
821 return false;
822 }
823 }
824 free(bits);
825 }
826#endif //CXIMAGE_SUPPORT_ALPHA
827 break;
828 }
829 case 24:
830 {
831 BYTE *buffer = (BYTE *)malloc(info.dwEffWidth);
832 if (!buffer) return false;
833 for (y = 0; y < height; y++) {
834 // get a pointer to the scanline
835 memcpy(buffer, info.pImage + (height - y - 1)*info.dwEffWidth, info.dwEffWidth);
836 // TIFFs store color data RGB instead of BGR
837 BYTE *pBuf = buffer;
838 for (x = 0; x < width; x++) {
839 BYTE tmp = pBuf[0];
840 pBuf[0] = pBuf[2];
841 pBuf[2] = tmp;
842 pBuf += 3;
843 }
844 // write the scanline to disc
845 if (TIFFWriteScanline(m_tif, buffer, y, 0)==-1){
846 free(buffer);
847 return false;
848 }
849 }
850 free(buffer);
851 break;
852 }
853 case 32 :
854 {
855#if CXIMAGE_SUPPORT_ALPHA
856 BYTE *buffer = (BYTE *)malloc((info.dwEffWidth*4)/3);
857 if (!buffer) return false;
858 for (y = 0; y < height; y++) {
859 // get a pointer to the scanline
860 memcpy(buffer, info.pImage + (height - y - 1)*info.dwEffWidth, info.dwEffWidth);
861 // TIFFs store color data RGB instead of BGR
862 BYTE *pSrc = buffer + 3 * width;
863 BYTE *pDst = buffer + 4 * width;
864 for (x = 0; x < width; x++) {
865 pDst-=4;
866 pSrc-=3;
867 pDst[3] = AlphaGet(width-x-1,height-y-1);
868 pDst[2] = pSrc[0];
869 pDst[1] = pSrc[1];
870 pDst[0] = pSrc[2];
871 }
872 // write the scanline to disc
873 if (TIFFWriteScanline(m_tif, buffer, y, 0)==-1){
874 free(buffer);
875 return false;
876 }
877 }
878 free(buffer);
879#endif //CXIMAGE_SUPPORT_ALPHA
880 break;
881 }
882 }
883 return true;
884}
885////////////////////////////////////////////////////////////////////////////////
886#endif // CXIMAGE_SUPPORT_ENCODE
887////////////////////////////////////////////////////////////////////////////////
888void CxImageTIF::TileToStrip(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew)
889{
890 while (rows-- > 0) {
891 uint32 j = cols;
892 while (j-- > 0)
893 *out++ = *in++;
894 out += outskew;
895 in += inskew;
896 }
897}
898////////////////////////////////////////////////////////////////////////////////
899TIFF* CxImageTIF::TIFFOpenEx(CxFile * hFile)
900{
901 if (hFile) return _TIFFOpenEx(hFile, "rb");
902 return NULL;
903}
904////////////////////////////////////////////////////////////////////////////////
905void CxImageTIF::TIFFCloseEx(TIFF* tif)
906{
907 if (tif) TIFFClose(tif);
908}
909////////////////////////////////////////////////////////////////////////////////
910void CxImageTIF::MoveBits( BYTE* dest, BYTE* from, int count, int bpp )
911{ int offbits = 0;
912 uint16 w;
913 uint32 d;
914 if (bpp <= 8) {
915 while (count-- > 0) {
916 if (offbits + bpp <= 8)
917 w = *from >> (8 - offbits - bpp);
918 else {
919 w = *from++ << (offbits + bpp - 8);
920 w |= *from >> (16 - offbits - bpp);
921 }
922 offbits += bpp;
923 if (offbits >= 8) {
924 offbits -= 8;
925 if (offbits == 0) from++;
926 }
927 *dest++ = (BYTE)w & ((1 << bpp)-1);
928 }
929 } else if (bpp < 16) {
930 while (count-- > 0) {
931 d = (*from << 24) | (from[1]<<16) | (from[2]<<8) | from[3];
932 d >>= (24 - offbits);
933 *dest++ = (BYTE) ( d );
934 offbits += bpp;
935 while (offbits >= 8) {
936 from++;
937 offbits -= 8;
938 }
939 }
940 } else if (bpp < 32) {
941 while (count-- > 0) {
942 d = (*from << 24) | (from[1]<<16) | (from[2]<<8) | from[3];
943 //d = *(uint32*)from;
944 *dest++ = (BYTE) ( d >> (offbits + bpp - 8) );
945 offbits += bpp;
946 while (offbits >= 8) {
947 from++;
948 offbits -= 8;
949 }
950 }
951 } else {
952 while (count-- > 0) {
953 d = *(uint32*)from;
954 *dest++ = (BYTE) (d >> 24);
955 from += 4;
956 }
957 }
958}
959////////////////////////////////////////////////////////////////////////////////
960void CxImageTIF::MoveBitsPal( BYTE* dest, BYTE*from, int count, int bpp, RGBQUAD* pal )
961{ int offbits = 0;
962 uint32 d;
963 uint16 palidx;
964 while (count-- > 0) {
965 d = (*from << 24) | ( *( from + 1 ) << 16 )
966 | ( *( from + 2 ) << 8 )
967 | ( *( from + 3 ) );
968 palidx = (uint16) (d >> (32 - offbits - bpp));
969 if (bpp < 16) {
970 palidx <<= 16-bpp;
971 palidx = (palidx >> 8) | (palidx <<8);
972 palidx >>= 16-bpp;
973 } else palidx = (palidx >> 8) | (palidx << 8);
974 *dest++ = pal[palidx].rgbBlue;
975 *dest++ = pal[palidx].rgbGreen;
976 *dest++ = pal[palidx].rgbRed;
977 offbits += bpp;
978 while (offbits >= 8) {
979 from++;
980 offbits -= 8;
981 }
982 }
983}
984////////////////////////////////////////////////////////////////////////////////
985
986#endif // CXIMAGE_SUPPORT_TIF
Note: See TracBrowser for help on using the repository browser.