]> Creatis software - clitk.git/blob - utilities/CxImage/ximatif.cpp
cosmetic
[clitk.git] / utilities / CxImage / ximatif.cpp
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
21 extern "C" TIFF* _TIFFOpenEx(CxFile* stream, const char* mode);
22
23 ////////////////////////////////////////////////////////////////////////////////
24 CxImageTIF::~CxImageTIF()
25 {
26         if (m_tif2) TIFFClose(m_tif2);
27 }
28 ////////////////////////////////////////////////////////////////////////////////
29 #if CXIMAGE_SUPPORT_DECODE
30 ////////////////////////////////////////////////////////////////////////////////
31 bool 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                 if ((bitspersample > 8) && (bitspersample != 16))       // + VK (for bitspersample == 9..15,17..32..64
281                         bitsize *= (bitspersample + 7)/8; 
282
283                 int tiled_image = TIFFIsTiled(m_tif);
284                 uint32 tw=0, tl=0;
285                 BYTE* tilebuf=NULL;
286                 if (tiled_image){
287                         TIFFGetField(m_tif, TIFFTAG_TILEWIDTH, &tw);
288                         TIFFGetField(m_tif, TIFFTAG_TILELENGTH, &tl);
289                         rowsperstrip = tl;
290                         bitsize = TIFFTileSize(m_tif) * (int)(1+width/tw);
291                         tilebuf = (BYTE*)malloc(TIFFTileSize(m_tif));
292                 }
293                 
294                 bits = (BYTE*)malloc(bitspersample==16? bitsize*2 : bitsize); // * VK
295                 BYTE * bits16 = NULL;                                                                             // + VK
296                 int line16    = 0;                                                                                        // + VK
297
298                 if (!tiled_image && bitspersample==16) {                                          // + VK +
299                         line16 = line;
300                         line   = CalculateLine(width, 8 * samplesperpixel);
301                         bits16 = bits;
302                         bits   = (BYTE*)malloc(bitsize);
303                 }
304
305                 if (bits==NULL){
306                         if (bits16) free(bits16);                                                                 // + VK
307                         if (pal)        free(pal);                                                                        // + VK
308                         if (tilebuf)free(tilebuf);                                                                // + VK       
309                         cx_throw("CxImageTIF can't allocate memory");
310                 }
311
312 #ifdef FIX_16BPP_DARKIMG // + VK: for each line, store shift count bits used to fix it
313                 BYTE* row_shifts = NULL;
314                 if (bits16) row_shifts = (BYTE*)malloc(height); 
315 #endif
316
317                 for (ys = 0; ys < height; ys += rowsperstrip) {
318
319                         if (info.nEscape){ // <vho> - cancel decoding
320                                 free(bits);
321                                 cx_throw("Cancelled");
322                         }
323
324                         nrow = (ys + rowsperstrip > height ? height - ys : rowsperstrip);
325
326                         if (tiled_image){
327                                 uint32 imagew = TIFFScanlineSize(m_tif);
328                                 uint32 tilew  = TIFFTileRowSize(m_tif);
329                                 int iskew = imagew - tilew;
330                                 uint8* bufp = (uint8*) bits;
331
332                                 uint32 colb = 0;
333                                 for (uint32 col = 0; col < width; col += tw) {
334                                         if (TIFFReadTile(m_tif, tilebuf, col, ys, 0, 0) < 0){
335                                                 free(tilebuf);
336                                                 free(bits);
337                                                 cx_throw("Corrupted tiled TIFF file!");
338                                         }
339
340                                         if (colb + tw > imagew) {
341                                                 uint32 owidth = imagew - colb;
342                                                 uint32 oskew = tilew - owidth;
343                                                 TileToStrip(bufp + colb, tilebuf, nrow, owidth, oskew + iskew, oskew );
344                                         } else {
345                                                 TileToStrip(bufp + colb, tilebuf, nrow, tilew, iskew, 0);
346                                         }
347                                         colb += tilew;
348                                 }
349
350                         } else {
351                                 if (TIFFReadEncodedStrip(m_tif, TIFFComputeStrip(m_tif, ys, 0), 
352                                         (bits16? bits16 : bits), nrow * (bits16 ? line16 : line)) == -1) { // * VK
353
354 #ifdef NOT_IGNORE_CORRUPTED
355                                         free(bits);
356                                         if (bits16) free(bits16);  // + VK
357                                         cx_throw("Corrupted TIFF file!");
358 #else
359                                         break;
360 #endif
361                                 }
362                         }
363
364                         for (y = 0; y < nrow; y++) {
365                                 long offset=(nrow-y-1)*line;
366                                 if ((bitspersample==16) && !BIG_palette) {      // * VK
367                                         long offset16 = (nrow-y-1)*line16;              // + VK
368                                         if (bits16)     {                                                       // + VK +
369 #ifdef FIX_16BPP_DARKIMG
370                                                 int the_shift;
371                                                 BYTE hi_byte, hi_max=0;
372                                                 DWORD xi;
373                                                 for (xi=0;xi<(uint32)line;xi++) {
374                                                         hi_byte = bits16[xi*2+offset16+1];
375                                                         if(hi_byte>hi_max)
376                                                                 hi_max = hi_byte;
377                                                 }
378                                                 the_shift = (hi_max == 0) ? 8 : 0;
379                                                 if (!the_shift)
380                                                         while( ! (hi_max & 0x80) ) {
381                                                                 the_shift++;
382                                                                 hi_max <<= 1;
383                                                         }
384                                                 row_shifts[height-ys-nrow+y] = the_shift;
385                                                 the_shift = 8 - the_shift;
386                                                 for (xi=0;xi<(uint32)line;xi++) 
387                                                         bits[xi+offset]= ((bits16[xi*2+offset16+1]<<8) | bits16[xi*2+offset16]) >> the_shift;
388 #else
389                                                 for (DWORD xi=0;xi<(uint32)line;xi++) 
390                                                         bits[xi+offset]=bits16[xi*2+offset16+1];
391 #endif
392                                         } else {
393                                                 for (DWORD xi=0;xi<width;xi++)
394                                                         bits[xi+offset]=bits[xi*2+offset+1];
395                                                         }
396                                 }
397                                 if (samplesperpixel==1) { 
398                                         if (BIG_palette)
399                                                 if (bits16) {
400                                                         long offset16 = (nrow-y-1)*line16;              // + VK
401                                                         MoveBitsPal( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
402                                                                          bits16 + offset16, width, bitspersample, pal );
403                                                 } else
404                                                         MoveBitsPal( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
405                                                                          bits + offset, width, bitspersample, pal );
406                                         else if ((bitspersample == head.biBitCount) || 
407                                                 (bitspersample == 16))  //simple 8bpp, 4bpp image or 16bpp
408                                                 memcpy(info.pImage+info.dwEffWidth*(height-ys-nrow+y),bits+offset,info.dwEffWidth);
409                                         else
410                                                 MoveBits( info.pImage + info.dwEffWidth * (height-ys-nrow+y),
411                                                                   bits + offset, width, bitspersample );
412                                 } else if (samplesperpixel==2) { //8bpp image with alpha layer
413                                         int xi=0;
414                                         int ii=0;
415                                         int yi=height-ys-nrow+y;
416 #if CXIMAGE_SUPPORT_ALPHA
417                                         if (!pAlpha) AlphaCreate();                     // + VK
418 #endif //CXIMAGE_SUPPORT_ALPHA
419                                         while (ii<line){
420                                                 SetPixelIndex(xi,yi,bits[ii+offset]);
421 #if CXIMAGE_SUPPORT_ALPHA
422                                                 AlphaSet(xi,yi,bits[ii+offset+1]);
423 #endif //CXIMAGE_SUPPORT_ALPHA
424                                                 ii+=2;
425                                                 xi++;
426                                                 if (xi>=(int)width){
427                                                         yi--;
428                                                         xi=0;
429                                                 }
430                                         }
431                                 } else { //photometric==PHOTOMETRIC_CIELAB
432                                         if (head.biBitCount!=24){ //fix image
433                                                 Create(width,height,24,CXIMAGE_FORMAT_TIF);
434 #if CXIMAGE_SUPPORT_ALPHA
435                                                 if (samplesperpixel==4) AlphaCreate();
436 #endif //CXIMAGE_SUPPORT_ALPHA
437                                         }
438
439                                         int xi=0;
440                                         uint32 ii=0;
441                                         int yi=height-ys-nrow+y;
442                                         RGBQUAD c;
443                                         int l,a,b,bitsoffset;
444                                         double p,cx,cy,cz,cr,cg,cb;
445                                         while (ii</*line*/width){               // * VK
446                                                 bitsoffset = ii*samplesperpixel+offset;
447                                                 l=bits[bitsoffset];
448                                                 a=bits[bitsoffset+1];
449                                                 b=bits[bitsoffset+2];
450                                                 if (a>127) a-=256;
451                                                 if (b>127) b-=256;
452                                                 // lab to xyz
453                                                 p = (l/2.55 + 16) / 116.0;
454                                                 cx = pow( p + a * 0.002, 3);
455                                                 cy = pow( p, 3);
456                                                 cz = pow( p - b * 0.005, 3);
457                                                 // white point
458                                                 cx*=0.95047;
459                                                 //cy*=1.000;
460                                                 cz*=1.0883;
461                                                 // xyz to rgb
462                                                 cr =  3.240479 * cx - 1.537150 * cy - 0.498535 * cz;
463                                                 cg = -0.969256 * cx + 1.875992 * cy + 0.041556 * cz;
464                                                 cb =  0.055648 * cx - 0.204043 * cy + 1.057311 * cz;
465
466                                                 if ( cr > 0.00304 ) cr = 1.055 * pow(cr,0.41667) - 0.055;
467                                                         else            cr = 12.92 * cr;
468                                                 if ( cg > 0.00304 ) cg = 1.055 * pow(cg,0.41667) - 0.055;
469                                                         else            cg = 12.92 * cg;
470                                                 if ( cb > 0.00304 ) cb = 1.055 * pow(cb,0.41667) - 0.055;
471                                                         else            cb = 12.92 * cb;
472
473                                                 c.rgbRed  =(BYTE)max(0,min(255,(int)(cr*255)));
474                                                 c.rgbGreen=(BYTE)max(0,min(255,(int)(cg*255)));
475                                                 c.rgbBlue =(BYTE)max(0,min(255,(int)(cb*255)));
476
477                                                 SetPixelColor(xi,yi,c);
478 #if CXIMAGE_SUPPORT_ALPHA
479                                                 if (samplesperpixel==4) AlphaSet(xi,yi,bits[bitsoffset+3]);
480 #endif //CXIMAGE_SUPPORT_ALPHA
481                                                 ii++;
482                                                 xi++;
483                                                 if (xi>=(int)width){
484                                                         yi--;
485                                                         xi=0;
486                                                 }
487                                         }
488                                 }
489                         }
490                 }
491                 free(bits);
492                 if (bits16) free(bits16);
493
494 #ifdef FIX_16BPP_DARKIMG
495                 if (row_shifts && (samplesperpixel == 1) && (bitspersample==16) && !BIG_palette) {
496                         // 1. calculate maximum necessary shift
497                         int min_row_shift = 8;
498                         for( y=0; y<height; y++ ) {
499                                 if (min_row_shift > row_shifts[y]) min_row_shift = row_shifts[y];
500                         }
501                         // 2. for rows having less shift value, correct such rows:
502                         for( y=0; y<height; y++ ) {
503                                 if (min_row_shift < row_shifts[y]) {
504                                         int need_shift = row_shifts[y] - min_row_shift;
505                                         BYTE* data = info.pImage + info.dwEffWidth * y;
506                                         for( x=0; x<width; x++, data++ )
507                                                 *data >>= need_shift;
508                                 }
509                         }
510                 }
511                 if (row_shifts) free( row_shifts );
512 #endif
513
514                 if (tiled_image) free(tilebuf);
515                 if (pal)                 free(pal);
516
517                 switch(orientation){
518                 case ORIENTATION_TOPRIGHT: /* row 0 top, col 0 rhs */
519                         Mirror();
520                         break;
521                 case ORIENTATION_BOTRIGHT: /* row 0 bottom, col 0 rhs */
522                         Flip();
523                         Mirror();
524                         break;
525                 case ORIENTATION_BOTLEFT: /* row 0 bottom, col 0 lhs */
526                         Flip();
527                         break;
528                 case ORIENTATION_LEFTTOP: /* row 0 lhs, col 0 top */
529                         RotateRight();
530                         Mirror();
531                         break;
532                 case ORIENTATION_RIGHTTOP: /* row 0 rhs, col 0 top */
533                         RotateLeft();
534                         break;
535                 case ORIENTATION_RIGHTBOT: /* row 0 rhs, col 0 bottom */
536                         RotateLeft();
537                         Mirror();
538                         break;
539                 case ORIENTATION_LEFTBOT: /* row 0 lhs, col 0 bottom */
540                         RotateRight();
541                         break;
542                 }
543
544         }
545   } cx_catch {
546           if (strcmp(message,"")) strncpy(info.szLastError,message,255);
547           if (m_tif) TIFFClose(m_tif);
548           if (info.nEscape == -1 && info.dwType == CXIMAGE_FORMAT_TIF) return true;
549           return false;
550   }
551         TIFFClose(m_tif);
552         return true;
553 }
554 ////////////////////////////////////////////////////////////////////////////////
555 #endif //CXIMAGE_SUPPORT_DECODE
556 ////////////////////////////////////////////////////////////////////////////////
557 #if CXIMAGE_SUPPORT_ENCODE
558 ////////////////////////////////////////////////////////////////////////////////
559 bool CxImageTIF::Encode(CxFile * hFile, bool bAppend)
560 {
561   cx_try
562   {
563         if (hFile==NULL) cx_throw(CXIMAGE_ERR_NOFILE);
564         if (pDib==NULL) cx_throw(CXIMAGE_ERR_NOIMAGE);
565
566         // <RJ> replaced "w+b" with "a", to append an image directly on an existing file
567         if (m_tif2==NULL) m_tif2=_TIFFOpenEx(hFile, "a");
568         if (m_tif2==NULL) cx_throw("initialization fail");
569
570         if (bAppend || m_pages) m_multipage=true;
571         m_pages++;
572
573         if (!EncodeBody(m_tif2,m_multipage,m_pages,m_pages)) cx_throw("Error saving TIFF file");
574         if (bAppend) {
575                 if (!TIFFWriteDirectory(m_tif2)) cx_throw("Error saving TIFF directory");
576         }
577   } cx_catch {
578           if (strcmp(message,"")) strncpy(info.szLastError,message,255);
579           if (m_tif2){
580                   TIFFClose(m_tif2);
581                   m_tif2=NULL;
582                   m_multipage=false;
583                   m_pages=0;
584           }
585           return false;
586   }
587         if (!bAppend){
588                 TIFFClose(m_tif2);
589                 m_tif2=NULL;
590                 m_multipage=false;
591                 m_pages=0;
592         }
593         return true;
594 }
595 ////////////////////////////////////////////////////////////////////////////////
596 // Thanks to Abe <God(dot)bless(at)marihuana(dot)com>
597 bool CxImageTIF::Encode(CxFile * hFile, CxImage ** pImages, int pagecount)
598 {
599   cx_try
600   {
601         if (hFile==NULL) cx_throw("invalid file pointer");
602         if (pImages==NULL || pagecount<=0) cx_throw("multipage TIFF, no images!");
603
604         int i;
605         for (i=0; i<pagecount; i++){
606                 if (pImages[i]==NULL)
607                         cx_throw("Bad image pointer");
608                 if (!(pImages[i]->IsValid()))
609                         cx_throw("Empty image");
610         }
611
612         CxImageTIF ghost;
613         for (i=0; i<pagecount; i++){
614                 ghost.Ghost(pImages[i]);
615                 if (!ghost.Encode(hFile,true)) cx_throw("Error saving TIFF file");
616         }
617   } cx_catch {
618           if (strcmp(message,"")) strncpy(info.szLastError,message,255);
619           return false;
620   }
621         return true;
622 }
623 ////////////////////////////////////////////////////////////////////////////////
624 bool CxImageTIF::EncodeBody(TIFF *m_tif, bool multipage, int page, int pagecount)
625 {
626         uint32 height=head.biHeight;
627         uint32 width=head.biWidth;
628         uint16 bitcount=head.biBitCount;
629         uint16 bitspersample;
630         uint16 samplesperpixel;
631         uint16 photometric=0;
632         uint16 compression;
633 //      uint16 pitch;
634 //      int line;
635         uint32 x, y;
636
637         samplesperpixel = ((bitcount == 24) || (bitcount == 32)) ? (BYTE)3 : (BYTE)1;
638 #if CXIMAGE_SUPPORT_ALPHA
639         if (bitcount==24 && AlphaIsValid()) { bitcount=32; samplesperpixel=4; }
640 #endif //CXIMAGE_SUPPORT_ALPHA
641
642         bitspersample = bitcount / samplesperpixel;
643
644         //set the PHOTOMETRIC tag
645         RGBQUAD *rgb = GetPalette();
646         switch (bitcount) {
647                 case 1:
648                         if (CompareColors(&rgb[0],&rgb[1])<0) {
649                                 /* <abe> some viewers do not handle PHOTOMETRIC_MINISBLACK:
650                                  * let's transform the image in PHOTOMETRIC_MINISWHITE
651                                  */
652                                 //invert the colors
653                                 RGBQUAD tempRGB=GetPaletteColor(0);
654                                 SetPaletteColor(0,GetPaletteColor(1));
655                                 SetPaletteColor(1,tempRGB);
656                                 //invert the pixels
657                                 BYTE *iSrc=info.pImage;
658                                 for (unsigned long i=0;i<head.biSizeImage;i++){
659                                         *iSrc=(BYTE)~(*(iSrc));
660                                         iSrc++;
661                                 }
662                                 photometric = PHOTOMETRIC_MINISWHITE;
663                                 //photometric = PHOTOMETRIC_MINISBLACK;
664                         } else {
665                                 photometric = PHOTOMETRIC_MINISWHITE;
666                         }
667                         break;
668                 case 4: // Check if the DIB has a color or a greyscale palette
669                 case 8:
670                         photometric = PHOTOMETRIC_MINISBLACK; //default to gray scale
671                         for (x = 0; x < head.biClrUsed; x++) {
672                                 if ((rgb->rgbRed != x)||(rgb->rgbRed != rgb->rgbGreen)||(rgb->rgbRed != rgb->rgbBlue)){
673                                         photometric = PHOTOMETRIC_PALETTE;
674                                         break;
675                                 }
676                                 rgb++;
677                         }
678                         break;
679                 case 24:
680                 case 32:
681                         photometric = PHOTOMETRIC_RGB;                  
682                         break;
683         }
684
685 #if CXIMAGE_SUPPORT_ALPHA
686         if (AlphaIsValid() && bitcount==8) samplesperpixel=2; //8bpp + alpha layer
687 #endif //CXIMAGE_SUPPORT_ALPHA
688
689 //      line = CalculateLine(width, bitspersample * samplesperpixel);
690 //      pitch = (uint16)CalculatePitch(line);
691
692         //prepare the palette struct
693         RGBQUAD pal[256];
694         if (GetPalette()){
695                 BYTE b;
696                 memcpy(pal,GetPalette(),GetPaletteSize());
697                 for(WORD a=0;a<head.biClrUsed;a++){     //swap blue and red components
698                         b=pal[a].rgbBlue; pal[a].rgbBlue=pal[a].rgbRed; pal[a].rgbRed=b;
699                 }
700         }
701
702         // handle standard width/height/bpp stuff
703         TIFFSetField(m_tif, TIFFTAG_IMAGEWIDTH, width);
704         TIFFSetField(m_tif, TIFFTAG_IMAGELENGTH, height);
705         TIFFSetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
706         TIFFSetField(m_tif, TIFFTAG_BITSPERSAMPLE, bitspersample);
707         TIFFSetField(m_tif, TIFFTAG_PHOTOMETRIC, photometric);
708         TIFFSetField(m_tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); // single image plane 
709         TIFFSetField(m_tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
710
711         uint32 rowsperstrip = TIFFDefaultStripSize(m_tif, (uint32) -1);  //<REC> gives better compression
712         TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
713
714         // handle metrics
715         TIFFSetField(m_tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
716         TIFFSetField(m_tif, TIFFTAG_XRESOLUTION, (float)info.xDPI);
717         TIFFSetField(m_tif, TIFFTAG_YRESOLUTION, (float)info.yDPI);
718 //      TIFFSetField(m_tif, TIFFTAG_XPOSITION, (float)info.xOffset);
719 //      TIFFSetField(m_tif, TIFFTAG_YPOSITION, (float)info.yOffset);
720
721         // multi-paging - Thanks to Abe <God(dot)bless(at)marihuana(dot)com>
722         if (multipage)
723         {
724                 char page_number[20];
725                 sprintf(page_number, "Page %d", page);
726
727                 TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
728                 TIFFSetField(m_tif, TIFFTAG_PAGENUMBER, page,pagecount);
729                 TIFFSetField(m_tif, TIFFTAG_PAGENAME, page_number);
730         } else {
731                 TIFFSetField(m_tif, TIFFTAG_SUBFILETYPE, 0);
732         }
733
734         // palettes (image colormaps are automatically scaled to 16-bits)
735         if (photometric == PHOTOMETRIC_PALETTE) {
736                 uint16 *r, *g, *b;
737                 r = (uint16 *) _TIFFmalloc(sizeof(uint16) * 3 * 256);
738                 g = r + 256;
739                 b = g + 256;
740
741                 for (int i = 255; i >= 0; i--) {
742                         b[i] = (uint16)SCALE((uint16)pal[i].rgbRed);
743                         g[i] = (uint16)SCALE((uint16)pal[i].rgbGreen);
744                         r[i] = (uint16)SCALE((uint16)pal[i].rgbBlue);
745                 }
746
747                 TIFFSetField(m_tif, TIFFTAG_COLORMAP, r, g, b);
748                 _TIFFfree(r);
749         }
750
751         // compression
752         if (GetCodecOption(CXIMAGE_FORMAT_TIF)) {
753                 compression = (WORD)GetCodecOption(CXIMAGE_FORMAT_TIF);
754         } else {
755                 switch (bitcount) {
756                         case 1 :
757                                 compression = COMPRESSION_CCITTFAX4;
758                                 break;
759                         case 4 :
760                         case 8 :
761                                 compression = COMPRESSION_LZW;
762                                 break;
763                         case 24 :
764                         case 32 :
765                                 compression = COMPRESSION_JPEG;
766                                 break;
767                         default :
768                                 compression = COMPRESSION_NONE;
769                                 break;
770                 }
771         }
772         TIFFSetField(m_tif, TIFFTAG_COMPRESSION, compression);
773
774         switch (compression) {
775         case COMPRESSION_JPEG:
776                 TIFFSetField(m_tif, TIFFTAG_JPEGQUALITY, GetJpegQuality());
777                 TIFFSetField(m_tif, TIFFTAG_ROWSPERSTRIP, ((7+rowsperstrip)>>3)<<3);
778                 break;
779         case COMPRESSION_LZW:
780                 if (bitcount>=8) TIFFSetField(m_tif, TIFFTAG_PREDICTOR, 2);
781                 break;
782         }
783
784         // read the DIB lines from bottom to top and save them in the TIF
785
786         BYTE *bits;
787         switch(bitcount) {                              
788                 case 1 :
789                 case 4 :
790                 case 8 :
791                 {
792                         if (samplesperpixel==1){
793                                 bits = (BYTE*)malloc(info.dwEffWidth);
794                                 if (!bits) return false;
795                                 for (y = 0; y < height; y++) {
796                                         memcpy(bits,info.pImage + (height - y - 1)*info.dwEffWidth,info.dwEffWidth);
797                                         if (TIFFWriteScanline(m_tif,bits, y, 0)==-1){
798                                                 free(bits);
799                                                 return false;
800                                         }
801                                 }
802                                 free(bits);
803                         }
804 #if CXIMAGE_SUPPORT_ALPHA
805                         else { //8bpp + alpha layer
806                                 bits = (BYTE*)malloc(2*width);
807                                 if (!bits) return false;
808                                 for (y = 0; y < height; y++) {
809                                         for (x=0;x<width;x++){
810                                                 bits[2*x]=BlindGetPixelIndex(x,height - y - 1);
811                                                 bits[2*x+1]=AlphaGet(x,height - y - 1);
812                                         }
813                                         if (TIFFWriteScanline(m_tif,bits, y, 0)==-1) {
814                                                 free(bits);
815                                                 return false;
816                                         }
817                                 }
818                                 free(bits);
819                         }
820 #endif //CXIMAGE_SUPPORT_ALPHA
821                         break;
822                 }                               
823                 case 24:
824                 {
825                         BYTE *buffer = (BYTE *)malloc(info.dwEffWidth);
826                         if (!buffer) return false;
827                         for (y = 0; y < height; y++) {
828                                 // get a pointer to the scanline
829                                 memcpy(buffer, info.pImage + (height - y - 1)*info.dwEffWidth, info.dwEffWidth);
830                                 // TIFFs store color data RGB instead of BGR
831                                 BYTE *pBuf = buffer;
832                                 for (x = 0; x < width; x++) {
833                                         BYTE tmp = pBuf[0];
834                                         pBuf[0] = pBuf[2];
835                                         pBuf[2] = tmp;
836                                         pBuf += 3;
837                                 }
838                                 // write the scanline to disc
839                                 if (TIFFWriteScanline(m_tif, buffer, y, 0)==-1){
840                                         free(buffer);
841                                         return false;
842                                 }
843                         }
844                         free(buffer);
845                         break;
846                 }                               
847                 case 32 :
848                 {
849 #if CXIMAGE_SUPPORT_ALPHA
850                         BYTE *buffer = (BYTE *)malloc((info.dwEffWidth*4)/3);
851                         if (!buffer) return false;
852                         for (y = 0; y < height; y++) {
853                                 // get a pointer to the scanline
854                                 memcpy(buffer, info.pImage + (height - y - 1)*info.dwEffWidth, info.dwEffWidth);
855                                 // TIFFs store color data RGB instead of BGR
856                                 BYTE *pSrc = buffer + 3 * width;
857                                 BYTE *pDst = buffer + 4 * width;
858                                 for (x = 0; x < width; x++) {
859                                         pDst-=4;
860                                         pSrc-=3;
861                                         pDst[3] = AlphaGet(width-x-1,height-y-1);
862                                         pDst[2] = pSrc[0];
863                                         pDst[1] = pSrc[1];
864                                         pDst[0] = pSrc[2];
865                                 }
866                                 // write the scanline to disc
867                                 if (TIFFWriteScanline(m_tif, buffer, y, 0)==-1){
868                                         free(buffer);
869                                         return false;
870                                 }
871                         }
872                         free(buffer);
873 #endif //CXIMAGE_SUPPORT_ALPHA
874                         break;
875                 }                               
876         }
877         return true;
878 }
879 ////////////////////////////////////////////////////////////////////////////////
880 #endif // CXIMAGE_SUPPORT_ENCODE
881 ////////////////////////////////////////////////////////////////////////////////
882 void CxImageTIF::TileToStrip(uint8* out, uint8* in,     uint32 rows, uint32 cols, int outskew, int inskew)
883 {
884         while (rows-- > 0) {
885                 uint32 j = cols;
886                 while (j-- > 0)
887                         *out++ = *in++;
888                 out += outskew;
889                 in += inskew;
890         }
891 }
892 ////////////////////////////////////////////////////////////////////////////////
893 TIFF* CxImageTIF::TIFFOpenEx(CxFile * hFile)
894 {
895         if (hFile) return _TIFFOpenEx(hFile, "rb");
896         return NULL;
897 }
898 ////////////////////////////////////////////////////////////////////////////////
899 void CxImageTIF::TIFFCloseEx(TIFF* tif)
900 {
901         if (tif) TIFFClose(tif);
902 }
903 ////////////////////////////////////////////////////////////////////////////////
904 void CxImageTIF::MoveBits( BYTE* dest, BYTE* from, int count, int bpp )
905 {       int offbits = 0;
906         uint16 w;
907         uint32 d;
908         if (bpp <= 8) {
909                 while (count-- > 0) {
910                         if (offbits + bpp <= 8)
911                                 w = *from >> (8 - offbits - bpp);
912                         else {
913                         w = *from++ << (offbits + bpp - 8);
914                                 w |= *from >> (16 - offbits - bpp);
915                         }
916                         offbits += bpp;
917                         if (offbits >= 8) {
918                                 offbits -= 8;
919                         if (offbits == 0) from++;
920                         }       
921                         *dest++ = (BYTE)w & ((1 << bpp)-1);
922                 }
923         } else if (bpp < 16) {
924                 while (count-- > 0) {
925                         d = (*from << 24) | (from[1]<<16) | (from[2]<<8) | from[3];
926                         d >>= (24 - offbits);
927                         *dest++ = (BYTE) ( d );
928                         offbits += bpp;
929                         while (offbits >= 8) {
930                                 from++;
931                                 offbits -= 8;
932                         }
933                 }
934         } else if (bpp < 32) {
935                 while (count-- > 0) {
936                         d = (*from << 24) | (from[1]<<16) | (from[2]<<8) | from[3];
937                         //d = *(uint32*)from;
938                         *dest++ = (BYTE) ( d >> (offbits + bpp - 8) );
939                         offbits += bpp;
940                         while (offbits >= 8) {
941                                 from++;
942                                 offbits -= 8;
943                         }
944                 }
945         } else {
946                 while (count-- > 0) {
947                         d = *(uint32*)from;
948                         *dest++ = (BYTE) (d >> 24);
949                         from += 4;
950                 }
951         }
952 }
953 ////////////////////////////////////////////////////////////////////////////////
954 void CxImageTIF::MoveBitsPal( BYTE* dest, BYTE*from, int count, int bpp, RGBQUAD* pal )
955 {       int offbits = 0;
956         uint32 d;
957         uint16 palidx;
958         while (count-- > 0) {
959                 d = (*from << 24) | ( *( from + 1 ) << 16 )
960                                                   | ( *( from + 2 ) << 8 )
961                                                   | ( *( from + 3 ) );
962                 palidx = (uint16) (d >> (32 - offbits - bpp));
963                 if (bpp < 16) {
964                         palidx <<= 16-bpp;
965                         palidx = (palidx >> 8) | (palidx <<8);
966                         palidx >>= 16-bpp;
967                 } else palidx = (palidx >> 8) | (palidx << 8);
968                 *dest++ = pal[palidx].rgbBlue;
969                 *dest++ = pal[palidx].rgbGreen;
970                 *dest++ = pal[palidx].rgbRed;
971                 offbits += bpp;
972                 while (offbits >= 8) {
973                         from++;
974                         offbits -= 8;
975                 }
976         }
977 }
978 ////////////////////////////////////////////////////////////////////////////////
979
980 #endif // CXIMAGE_SUPPORT_TIF