grfmt_tiff.cpp 24.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

/****************************************************************************************\
    A part of the file implements TIFF reader on base of libtiff library
    (see otherlibs/_graphics/readme.txt for copyright notice)
\****************************************************************************************/

#include "precomp.hpp"
#include "grfmt_tiff.hpp"

namespace cv
{
static const char fmtSignTiffII[] = "II\x2a\x00";
static const char fmtSignTiffMM[] = "MM\x00\x2a";

#ifdef HAVE_TIFF

#include "tiff.h"
#include "tiffio.h"

static int grfmt_tiff_err_handler_init = 0;
static void GrFmtSilentTIFFErrorHandler( const char*, const char*, va_list ) {}

TiffDecoder::TiffDecoder()
{
    m_tif = 0;
    if( !grfmt_tiff_err_handler_init )
    {
        grfmt_tiff_err_handler_init = 1;

        TIFFSetErrorHandler( GrFmtSilentTIFFErrorHandler );
        TIFFSetWarningHandler( GrFmtSilentTIFFErrorHandler );
    }
}


void TiffDecoder::close()
{
    if( m_tif )
    {
        TIFF* tif = (TIFF*)m_tif;
        TIFFClose( tif );
        m_tif = 0;
    }
}

TiffDecoder::~TiffDecoder()
{
    close();
}

size_t TiffDecoder::signatureLength() const
{
    return 4;
}

97
bool TiffDecoder::checkSignature( const String& signature ) const
98 99 100 101 102 103
{
    return signature.size() >= 4 &&
        (memcmp(signature.c_str(), fmtSignTiffII, 4) == 0 ||
        memcmp(signature.c_str(), fmtSignTiffMM, 4) == 0);
}

104 105 106 107 108
int TiffDecoder::normalizeChannelsNumber(int channels) const
{
    return channels > 4 ? 4 : channels;
}

109 110
ImageDecoder TiffDecoder::newDecoder() const
{
R
Roman Donchenko 已提交
111
    return makePtr<TiffDecoder>();
112 113 114 115 116 117 118 119 120 121 122
}

bool TiffDecoder::readHeader()
{
    bool result = false;

    close();
    TIFF* tif = TIFFOpen( m_filename.c_str(), "rb" );

    if( tif )
    {
A
Andrey Kamaev 已提交
123
        int wdth = 0, hght = 0, photometric = 0;
124 125
        m_tif = tif;

A
Andrey Kamaev 已提交
126 127
        if( TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &wdth ) &&
            TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &hght ) &&
128
            TIFFGetField( tif, TIFFTAG_PHOTOMETRIC, &photometric ))
129
        {
130 131 132
            int bpp=8, ncn = photometric > 1 ? 3 : 1;
            TIFFGetField( tif, TIFFTAG_BITSPERSAMPLE, &bpp );
            TIFFGetField( tif, TIFFTAG_SAMPLESPERPIXEL, &ncn );
A
Andrey Kamaev 已提交
133 134 135

            m_width = wdth;
            m_height = hght;
136 137 138 139
            if( bpp > 8 &&
               ((photometric != 2 && photometric != 1) ||
                (ncn != 1 && ncn != 3 && ncn != 4)))
                bpp = 8;
140

141
            int wanted_channels = normalizeChannelsNumber(ncn);
142 143 144
            switch(bpp)
            {
                case 8:
145
                    m_type = CV_MAKETYPE(CV_8U, photometric > 1 ? wanted_channels : 1);
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
                    break;
                case 16:
                    m_type = CV_MAKETYPE(CV_16U, photometric > 1 ? 3 : 1);
                    break;

                case 32:
                    m_type = CV_MAKETYPE(CV_32F, photometric > 1 ? 3 : 1);
                    break;
                case 64:
                    m_type = CV_MAKETYPE(CV_64F, photometric > 1 ? 3 : 1);
                    break;

                default:
                    result = false;
            }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            result = true;
        }
    }

    if( !result )
        close();

    return result;
}


bool  TiffDecoder::readData( Mat& img )
{
    bool result = false;
    bool color = img.channels() > 1;
    uchar* data = img.data;
A
Andrey Kamaev 已提交
177

178
    if( img.depth() != CV_8U && img.depth() != CV_16U && img.depth() != CV_32F && img.depth() != CV_64F )
179
        return false;
180 181 182 183 184 185 186

    if( m_tif && m_width && m_height )
    {
        TIFF* tif = (TIFF*)m_tif;
        int tile_width0 = m_width, tile_height0 = 0;
        int x, y, i;
        int is_tiled = TIFFIsTiled(tif);
187 188 189 190 191
        int photometric;
        TIFFGetField( tif, TIFFTAG_PHOTOMETRIC, &photometric );
        int bpp = 8, ncn = photometric > 1 ? 3 : 1;
        TIFFGetField( tif, TIFFTAG_BITSPERSAMPLE, &bpp );
        TIFFGetField( tif, TIFFTAG_SAMPLESPERPIXEL, &ncn );
192
        const int bitsPerByte = 8;
193
        int dst_bpp = (int)(img.elemSize1() * bitsPerByte);
194
        int wanted_channels = normalizeChannelsNumber(img.channels());
195 196 197 198 199 200 201 202 203 204

        if(dst_bpp == 8)
        {
            char errmsg[1024];
            if(!TIFFRGBAImageOK( tif, errmsg ))
            {
                close();
                return false;
            }
        }
205

206
        if( (!is_tiled) ||
207 208 209 210
            (is_tiled &&
            TIFFGetField( tif, TIFFTAG_TILEWIDTH, &tile_width0 ) &&
            TIFFGetField( tif, TIFFTAG_TILELENGTH, &tile_height0 )))
        {
211 212 213
            if(!is_tiled)
                TIFFGetField( tif, TIFFTAG_ROWSPERSTRIP, &tile_height0 );

214 215 216 217 218 219
            if( tile_width0 <= 0 )
                tile_width0 = m_width;

            if( tile_height0 <= 0 )
                tile_height0 = m_height;

220
            AutoBuffer<uchar> _buffer( size_t(8) * tile_height0*tile_width0);
221
            uchar* buffer = _buffer;
222
            ushort* buffer16 = (ushort*)buffer;
223 224
            float* buffer32 = (float*)buffer;
            double* buffer64 = (double*)buffer;
225
            int tileidx = 0;
226

227
            for( y = 0; y < m_height; y += tile_height0, data += img.step*tile_height0 )
228 229 230 231 232 233
            {
                int tile_height = tile_height0;

                if( y + tile_height > m_height )
                    tile_height = m_height - y;

234
                for( x = 0; x < m_width; x += tile_width0, tileidx++ )
235 236 237 238 239 240
                {
                    int tile_width = tile_width0, ok;

                    if( x + tile_width > m_width )
                        tile_width = m_width - x;

241
                    switch(dst_bpp)
242
                    {
243
                        case 8:
244
                        {
245 246
                            if( !is_tiled )
                                ok = TIFFReadRGBAStrip( tif, y, (uint32*)buffer );
247
                            else
248 249 250 251 252 253 254 255 256 257
                                ok = TIFFReadRGBATile( tif, x, y, (uint32*)buffer );

                            if( !ok )
                            {
                                close();
                                return false;
                            }

                            for( i = 0; i < tile_height; i++ )
                                if( color )
258 259 260 261 262 263 264 265 266 267
                                {
                                    if (wanted_channels == 4)
                                    {
                                        icvCvt_BGRA2RGBA_8u_C4R( buffer + i*tile_width*4, 0,
                                                             data + x*4 + img.step*(tile_height - i - 1), 0,
                                                             cvSize(tile_width,1) );
                                    }
                                    else
                                    {
                                        icvCvt_BGRA2BGR_8u_C4C3R( buffer + i*tile_width*4, 0,
268
                                                             data + x*3 + img.step*(tile_height - i - 1), 0,
269
                                                             cvSize(tile_width,1), 2 );
270 271
                                    }
                                }
272 273
                                else
                                    icvCvt_BGRA2Gray_8u_C4C1R( buffer + i*tile_width*4, 0,
274
                                                              data + x + img.step*(tile_height - i - 1), 0,
275 276
                                                              cvSize(tile_width,1), 2 );
                            break;
277
                        }
278 279

                        case 16:
280
                        {
281 282 283 284 285 286
                            if( !is_tiled )
                                ok = (int)TIFFReadEncodedStrip( tif, tileidx, (uint32*)buffer, (tsize_t)-1 ) >= 0;
                            else
                                ok = (int)TIFFReadEncodedTile( tif, tileidx, (uint32*)buffer, (tsize_t)-1 ) >= 0;

                            if( !ok )
287
                            {
288 289 290 291 292 293 294
                                close();
                                return false;
                            }

                            for( i = 0; i < tile_height; i++ )
                            {
                                if( color )
295
                                {
296 297 298
                                    if( ncn == 1 )
                                    {
                                        icvCvt_Gray2BGR_16u_C1C3R(buffer16 + i*tile_width*ncn, 0,
299
                                                                  (ushort*)(data + img.step*i) + x*3, 0,
300 301 302 303 304
                                                                  cvSize(tile_width,1) );
                                    }
                                    else if( ncn == 3 )
                                    {
                                        icvCvt_RGB2BGR_16u_C3R(buffer16 + i*tile_width*ncn, 0,
305
                                                               (ushort*)(data + img.step*i) + x*3, 0,
306 307 308 309 310
                                                               cvSize(tile_width,1) );
                                    }
                                    else
                                    {
                                        icvCvt_BGRA2BGR_16u_C4C3R(buffer16 + i*tile_width*ncn, 0,
311
                                                               (ushort*)(data + img.step*i) + x*3, 0,
312 313
                                                               cvSize(tile_width,1), 2 );
                                    }
314 315 316
                                }
                                else
                                {
317 318
                                    if( ncn == 1 )
                                    {
319
                                        memcpy((ushort*)(data + img.step*i)+x,
320 321 322 323 324 325
                                               buffer16 + i*tile_width*ncn,
                                               tile_width*sizeof(buffer16[0]));
                                    }
                                    else
                                    {
                                        icvCvt_BGRA2Gray_16u_CnC1R(buffer16 + i*tile_width*ncn, 0,
326
                                                               (ushort*)(data + img.step*i) + x, 0,
327 328
                                                               cvSize(tile_width,1), ncn, 2 );
                                    }
329 330
                                }
                            }
331 332 333 334 335 336 337 338
                            break;
                        }

                        case 32:
                        case 64:
                        {
                            if( !is_tiled )
                                ok = (int)TIFFReadEncodedStrip( tif, tileidx, buffer, (tsize_t)-1 ) >= 0;
339
                            else
340 341 342
                                ok = (int)TIFFReadEncodedTile( tif, tileidx, buffer, (tsize_t)-1 ) >= 0;

                            if( !ok || ncn != 1 )
343
                            {
344 345 346 347 348 349 350
                                close();
                                return false;
                            }

                            for( i = 0; i < tile_height; i++ )
                            {
                                if(dst_bpp == 32)
351
                                {
352
                                    memcpy((float*)(data + img.step*i)+x,
353 354
                                           buffer32 + i*tile_width*ncn,
                                           tile_width*sizeof(buffer32[0]));
355 356 357
                                }
                                else
                                {
358
                                    memcpy((double*)(data + img.step*i)+x,
359 360
                                         buffer64 + i*tile_width*ncn,
                                         tile_width*sizeof(buffer64[0]));
361 362
                                }
                            }
363 364

                            break;
365
                        }
366 367 368 369 370 371
                        default:
                        {
                            close();
                            return false;
                        }
                    }
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
                }
            }

            result = true;
        }
    }

    close();
    return result;
}

#endif

//////////////////////////////////////////////////////////////////////////////////////////

TiffEncoder::TiffEncoder()
{
    m_description = "TIFF Files (*.tiff;*.tif)";
390 391 392
#ifdef HAVE_TIFF
    m_buf_supported = false;
#else
393
    m_buf_supported = true;
394
#endif
395 396 397 398 399 400 401 402
}

TiffEncoder::~TiffEncoder()
{
}

ImageEncoder TiffEncoder::newEncoder() const
{
R
Roman Donchenko 已提交
403
    return makePtr<TiffEncoder>();
404 405
}

406 407 408 409 410
bool TiffEncoder::isFormatSupported( int depth ) const
{
    return depth == CV_8U || depth == CV_16U;
}

411 412 413 414 415 416 417 418 419 420
void  TiffEncoder::writeTag( WLByteStream& strm, TiffTag tag,
                             TiffFieldType fieldType,
                             int count, int value )
{
    strm.putWord( tag );
    strm.putWord( fieldType );
    strm.putDWord( count );
    strm.putDWord( value );
}

421
#ifdef HAVE_TIFF
422

423
static void readParam(const std::vector<int>& params, int key, int& value)
424 425 426 427 428 429 430 431 432
{
    for(size_t i = 0; i + 1 < params.size(); i += 2)
        if(params[i] == key)
        {
            value = params[i+1];
            break;
        }
}

433
bool  TiffEncoder::writeLibTiff( const Mat& img, const std::vector<int>& params)
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
{
    int channels = img.channels();
    int width = img.cols, height = img.rows;
    int depth = img.depth();

    int bitsPerChannel = -1;
    switch (depth)
    {
        case CV_8U:
        {
            bitsPerChannel = 8;
            break;
        }
        case CV_16U:
        {
            bitsPerChannel = 16;
            break;
        }
        default:
        {
            return false;
A
Andrey Kamaev 已提交
455
        }
456
    }
A
Andrey Kamaev 已提交
457

458 459
    const int bitsPerByte = 8;
    size_t fileStep = (width * channels * bitsPerChannel) / bitsPerByte;
460

461
    int rowsPerStrip = (int)((1 << 13)/fileStep);
462
    readParam(params, TIFFTAG_ROWSPERSTRIP, rowsPerStrip);
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

    if( rowsPerStrip < 1 )
        rowsPerStrip = 1;

    if( rowsPerStrip > height )
        rowsPerStrip = height;


    // do NOT put "wb" as the mode, because the b means "big endian" mode, not "binary" mode.
    // http://www.remotesensing.org/libtiff/man/TIFFOpen.3tiff.html
    TIFF* pTiffHandle = TIFFOpen(m_filename.c_str(), "w");
    if (!pTiffHandle)
    {
        return false;
    }
A
Andrey Kamaev 已提交
478

479 480 481 482
    // defaults for now, maybe base them on params in the future
    int   compression  = COMPRESSION_LZW;
    int   predictor    = PREDICTOR_HORIZONTAL;

483 484 485
    readParam(params, TIFFTAG_COMPRESSION, compression);
    readParam(params, TIFFTAG_PREDICTOR, predictor);

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    int   colorspace = channels > 1 ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK;

    if ( !TIFFSetField(pTiffHandle, TIFFTAG_IMAGEWIDTH, width)
      || !TIFFSetField(pTiffHandle, TIFFTAG_IMAGELENGTH, height)
      || !TIFFSetField(pTiffHandle, TIFFTAG_BITSPERSAMPLE, bitsPerChannel)
      || !TIFFSetField(pTiffHandle, TIFFTAG_COMPRESSION, compression)
      || !TIFFSetField(pTiffHandle, TIFFTAG_PHOTOMETRIC, colorspace)
      || !TIFFSetField(pTiffHandle, TIFFTAG_SAMPLESPERPIXEL, channels)
      || !TIFFSetField(pTiffHandle, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)
      || !TIFFSetField(pTiffHandle, TIFFTAG_ROWSPERSTRIP, rowsPerStrip)
      || !TIFFSetField(pTiffHandle, TIFFTAG_PREDICTOR, predictor)
       )
    {
        TIFFClose(pTiffHandle);
        return false;
    }

    // row buffer, because TIFFWriteScanline modifies the original data!
    size_t scanlineSize = TIFFScanlineSize(pTiffHandle);
505
    AutoBuffer<uchar> _buffer(scanlineSize+32);
506 507 508 509 510 511
    uchar* buffer = _buffer;
    if (!buffer)
    {
        TIFFClose(pTiffHandle);
        return false;
    }
512

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    for (int y = 0; y < height; ++y)
    {
        switch(channels)
        {
            case 1:
            {
                memcpy(buffer, img.data + img.step * y, scanlineSize);
                break;
            }

            case 3:
            {
                if (depth == CV_8U)
                    icvCvt_BGR2RGB_8u_C3R( img.data + img.step*y, 0, buffer, 0, cvSize(width,1) );
                else
                    icvCvt_BGR2RGB_16u_C3R( (const ushort*)(img.data + img.step*y), 0, (ushort*)buffer, 0, cvSize(width,1) );
                break;
            }

            case 4:
            {
                if (depth == CV_8U)
                    icvCvt_BGRA2RGBA_8u_C4R( img.data + img.step*y, 0, buffer, 0, cvSize(width,1) );
                else
                    icvCvt_BGRA2RGBA_16u_C4R( (const ushort*)(img.data + img.step*y), 0, (ushort*)buffer, 0, cvSize(width,1) );
538
                break;
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            }

            default:
            {
                TIFFClose(pTiffHandle);
                return false;
            }
        }

        int writeResult = TIFFWriteScanline(pTiffHandle, buffer, y, 0);
        if (writeResult != 1)
        {
            TIFFClose(pTiffHandle);
            return false;
        }
    }
A
Andrey Kamaev 已提交
555

556 557 558 559 560 561 562
    TIFFClose(pTiffHandle);
    return true;
}

#endif

#ifdef HAVE_TIFF
563
bool  TiffEncoder::write( const Mat& img, const std::vector<int>& params)
564
#else
565
bool  TiffEncoder::write( const Mat& img, const std::vector<int>& /*params*/)
566
#endif
567 568 569
{
    int channels = img.channels();
    int width = img.cols, height = img.rows;
570 571 572 573 574 575 576 577
    int depth = img.depth();

    if (depth != CV_8U && depth != CV_16U)
        return false;

    int bytesPerChannel = depth == CV_8U ? 1 : 2;
    int fileStep = width * channels * bytesPerChannel;

578 579 580 581 582 583 584
    WLByteStream strm;

    if( m_buf )
    {
        if( !strm.open(*m_buf) )
            return false;
    }
A
Andrey Kamaev 已提交
585
    else
586 587 588 589 590 591 592 593
    {
#ifdef HAVE_TIFF
      return writeLibTiff(img, params);
#else
      if( !strm.open(m_filename) )
          return false;
#endif
    }
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

    int rowsPerStrip = (1 << 13)/fileStep;

    if( rowsPerStrip < 1 )
        rowsPerStrip = 1;

    if( rowsPerStrip > height )
        rowsPerStrip = height;

    int i, stripCount = (height + rowsPerStrip - 1) / rowsPerStrip;

    if( m_buf )
        m_buf->reserve( alignSize(stripCount*8 + fileStep*height + 256, 256) );

/*#if defined _DEBUG || !defined WIN32
    int uncompressedRowSize = rowsPerStrip * fileStep;
#endif*/
    int directoryOffset = 0;

613 614 615
    AutoBuffer<int> stripOffsets(stripCount);
    AutoBuffer<short> stripCounts(stripCount);
    AutoBuffer<uchar> _buffer(fileStep+32);
616 617 618
    uchar* buffer = _buffer;
    int  stripOffsetsOffset = 0;
    int  stripCountsOffset = 0;
619
    int  bitsPerSample = 8 * bytesPerChannel;
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    int  y = 0;

    strm.putBytes( fmtSignTiffII, 4 );
    strm.putDWord( directoryOffset );

    // write an image data first (the most reasonable way
    // for compressed images)
    for( i = 0; i < stripCount; i++ )
    {
        int limit = y + rowsPerStrip;

        if( limit > height )
            limit = height;

        stripOffsets[i] = strm.getPos();

        for( ; y < limit; y++ )
        {
            if( channels == 3 )
639
            {
640 641 642 643
                if (depth == CV_8U)
                    icvCvt_BGR2RGB_8u_C3R( img.data + img.step*y, 0, buffer, 0, cvSize(width,1) );
                else
                    icvCvt_BGR2RGB_16u_C3R( (const ushort*)(img.data + img.step*y), 0, (ushort*)buffer, 0, cvSize(width,1) );
644 645 646 647 648
            }
            else
            {
              if( channels == 4 )
              {
649 650 651 652
                if (depth == CV_8U)
                    icvCvt_BGRA2RGBA_8u_C4R( img.data + img.step*y, 0, buffer, 0, cvSize(width,1) );
                else
                    icvCvt_BGRA2RGBA_16u_C4R( (const ushort*)(img.data + img.step*y), 0, (ushort*)buffer, 0, cvSize(width,1) );
653 654
              }
            }
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

            strm.putBytes( channels > 1 ? buffer : img.data + img.step*y, fileStep );
        }

        stripCounts[i] = (short)(strm.getPos() - stripOffsets[i]);
        /*assert( stripCounts[i] == uncompressedRowSize ||
                stripCounts[i] < uncompressedRowSize &&
                i == stripCount - 1);*/
    }

    if( stripCount > 2 )
    {
        stripOffsetsOffset = strm.getPos();
        for( i = 0; i < stripCount; i++ )
            strm.putDWord( stripOffsets[i] );

        stripCountsOffset = strm.getPos();
        for( i = 0; i < stripCount; i++ )
            strm.putWord( stripCounts[i] );
    }
    else if(stripCount == 2)
    {
        stripOffsetsOffset = strm.getPos();
        for (i = 0; i < stripCount; i++)
        {
            strm.putDWord (stripOffsets [i]);
        }
        stripCountsOffset = stripCounts [0] + (stripCounts [1] << 16);
    }
    else
    {
        stripOffsetsOffset = stripOffsets[0];
        stripCountsOffset = stripCounts[0];
    }

    if( channels > 1 )
    {
692 693 694 695
        int bitsPerSamplePos = strm.getPos();
        strm.putWord(bitsPerSample);
        strm.putWord(bitsPerSample);
        strm.putWord(bitsPerSample);
696
        if( channels == 4 )
697 698
            strm.putWord(bitsPerSample);
        bitsPerSample = bitsPerSamplePos;
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    }

    directoryOffset = strm.getPos();

    // write header
    strm.putWord( 9 );

    /* warning: specification 5.0 of Tiff want to have tags in
       ascending order. This is a non-fatal error, but this cause
       warning with some tools. So, keep this in ascending order */

    writeTag( strm, TIFF_TAG_WIDTH, TIFF_TYPE_LONG, 1, width );
    writeTag( strm, TIFF_TAG_HEIGHT, TIFF_TYPE_LONG, 1, height );
    writeTag( strm, TIFF_TAG_BITS_PER_SAMPLE,
              TIFF_TYPE_SHORT, channels, bitsPerSample );
    writeTag( strm, TIFF_TAG_COMPRESSION, TIFF_TYPE_LONG, 1, TIFF_UNCOMP );
    writeTag( strm, TIFF_TAG_PHOTOMETRIC, TIFF_TYPE_SHORT, 1, channels > 1 ? 2 : 1 );

    writeTag( strm, TIFF_TAG_STRIP_OFFSETS, TIFF_TYPE_LONG,
              stripCount, stripOffsetsOffset );

    writeTag( strm, TIFF_TAG_SAMPLES_PER_PIXEL, TIFF_TYPE_SHORT, 1, channels );
    writeTag( strm, TIFF_TAG_ROWS_PER_STRIP, TIFF_TYPE_LONG, 1, rowsPerStrip );

    writeTag( strm, TIFF_TAG_STRIP_COUNTS,
              stripCount > 1 ? TIFF_TYPE_SHORT : TIFF_TYPE_LONG,
              stripCount, stripCountsOffset );

    strm.putDWord(0);
    strm.close();

    if( m_buf )
    {
        (*m_buf)[4] = (uchar)directoryOffset;
        (*m_buf)[5] = (uchar)(directoryOffset >> 8);
        (*m_buf)[6] = (uchar)(directoryOffset >> 16);
        (*m_buf)[7] = (uchar)(directoryOffset >> 24);
    }
    else
    {
        // write directory offset
        FILE* f = fopen( m_filename.c_str(), "r+b" );
        buffer[0] = (uchar)directoryOffset;
        buffer[1] = (uchar)(directoryOffset >> 8);
        buffer[2] = (uchar)(directoryOffset >> 16);
        buffer[3] = (uchar)(directoryOffset >> 24);

        fseek( f, 4, SEEK_SET );
        fwrite( buffer, 1, 4, f );
        fclose(f);
    }

    return true;
}

}