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