1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagtiff.cpp
3 // Purpose: wxImage TIFF handler
4 // Author: Robert Roebling
6 // Copyright: (c) Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
18 // For compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
25 #if wxUSE_IMAGE && wxUSE_LIBTIFF
27 #include "wx/imagtiff.h"
33 #include "wx/bitmap.h"
34 #include "wx/module.h"
35 #include "wx/wxcrtvararg.h"
41 #include "tif_config.h"
46 #include "wx/filefn.h"
47 #include "wx/wfstream.h"
49 #ifndef TIFFLINKAGEMODE
50 #if defined(__WATCOMC__) && defined(__WXMGL__)
51 #define TIFFLINKAGEMODE cdecl
53 #define TIFFLINKAGEMODE LINKAGEMODE
57 // ============================================================================
59 // ============================================================================
61 // ----------------------------------------------------------------------------
62 // TIFF library error/warning handlers
63 // ----------------------------------------------------------------------------
66 FormatTiffMessage(const char *module, const char *fmt
, va_list ap
)
69 if ( wxCRT_VsnprintfA(buf
, WXSIZEOF(buf
), fmt
, ap
) <= 0 )
71 // this isn't supposed to happen, but if it does, it's better
73 strcpy(buf
, "Incorrectly formatted TIFF message");
75 buf
[WXSIZEOF(buf
)-1] = 0; // make sure it is always NULL-terminated
79 msg
+= wxString::Format(_(" (in module \"%s\")"), module);
88 TIFFwxWarningHandler(const char* module, const char *fmt
, va_list ap
)
90 wxLogWarning("%s", FormatTiffMessage(module, fmt
, ap
));
94 TIFFwxErrorHandler(const char* module, const char *fmt
, va_list ap
)
96 wxLogError("%s", FormatTiffMessage(module, fmt
, ap
));
101 //-----------------------------------------------------------------------------
103 //-----------------------------------------------------------------------------
105 IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler
,wxImageHandler
)
107 wxTIFFHandler::wxTIFFHandler()
109 m_name
= wxT("TIFF file");
110 m_extension
= wxT("tif");
111 m_altExtensions
.Add(wxT("tiff"));
112 m_type
= wxBITMAP_TYPE_TIF
;
113 m_mime
= wxT("image/tiff");
114 TIFFSetWarningHandler((TIFFErrorHandler
) TIFFwxWarningHandler
);
115 TIFFSetErrorHandler((TIFFErrorHandler
) TIFFwxErrorHandler
);
120 // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
122 static toff_t
wxFileOffsetToTIFF(wxFileOffset ofs
)
124 if ( ofs
== wxInvalidOffset
)
127 toff_t tofs
= wx_truncate_cast(toff_t
, ofs
);
128 wxCHECK_MSG( (wxFileOffset
)tofs
== ofs
, (toff_t
)-1,
129 wxT("TIFF library doesn't support large files") );
134 // another helper to convert standard seek mode to our
135 static wxSeekMode
wxSeekModeFromTIFF(int whence
)
143 return wxFromCurrent
;
149 return wxFromCurrent
;
156 tsize_t TIFFLINKAGEMODE
157 wxTIFFNullProc(thandle_t
WXUNUSED(handle
),
158 tdata_t
WXUNUSED(buf
),
159 tsize_t
WXUNUSED(size
))
164 tsize_t TIFFLINKAGEMODE
165 wxTIFFReadProc(thandle_t handle
, tdata_t buf
, tsize_t size
)
167 wxInputStream
*stream
= (wxInputStream
*) handle
;
168 stream
->Read( (void*) buf
, (size_t) size
);
169 return wx_truncate_cast(tsize_t
, stream
->LastRead());
172 tsize_t TIFFLINKAGEMODE
173 wxTIFFWriteProc(thandle_t handle
, tdata_t buf
, tsize_t size
)
175 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
176 stream
->Write( (void*) buf
, (size_t) size
);
177 return wx_truncate_cast(tsize_t
, stream
->LastWrite());
180 toff_t TIFFLINKAGEMODE
181 wxTIFFSeekIProc(thandle_t handle
, toff_t off
, int whence
)
183 wxInputStream
*stream
= (wxInputStream
*) handle
;
185 return wxFileOffsetToTIFF(stream
->SeekI((wxFileOffset
)off
,
186 wxSeekModeFromTIFF(whence
)));
189 toff_t TIFFLINKAGEMODE
190 wxTIFFSeekOProc(thandle_t handle
, toff_t off
, int whence
)
192 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
194 return wxFileOffsetToTIFF(stream
->SeekO((wxFileOffset
)off
,
195 wxSeekModeFromTIFF(whence
)));
199 wxTIFFCloseIProc(thandle_t
WXUNUSED(handle
))
201 // there is no need to close the input stream
206 wxTIFFCloseOProc(thandle_t handle
)
208 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
210 return stream
->Close() ? 0 : -1;
213 toff_t TIFFLINKAGEMODE
214 wxTIFFSizeProc(thandle_t handle
)
216 wxStreamBase
*stream
= (wxStreamBase
*) handle
;
217 return (toff_t
) stream
->GetSize();
221 wxTIFFMapProc(thandle_t
WXUNUSED(handle
),
222 tdata_t
* WXUNUSED(pbase
),
223 toff_t
* WXUNUSED(psize
))
229 wxTIFFUnmapProc(thandle_t
WXUNUSED(handle
),
230 tdata_t
WXUNUSED(base
),
231 toff_t
WXUNUSED(size
))
238 TIFFwxOpen(wxInputStream
&stream
, const char* name
, const char* mode
)
240 TIFF
* tif
= TIFFClientOpen(name
, mode
,
242 wxTIFFReadProc
, wxTIFFNullProc
,
243 wxTIFFSeekIProc
, wxTIFFCloseIProc
, wxTIFFSizeProc
,
244 wxTIFFMapProc
, wxTIFFUnmapProc
);
250 TIFFwxOpen(wxOutputStream
&stream
, const char* name
, const char* mode
)
252 TIFF
* tif
= TIFFClientOpen(name
, mode
,
254 wxTIFFNullProc
, wxTIFFWriteProc
,
255 wxTIFFSeekOProc
, wxTIFFCloseOProc
, wxTIFFSizeProc
,
256 wxTIFFMapProc
, wxTIFFUnmapProc
);
261 bool wxTIFFHandler::LoadFile( wxImage
*image
, wxInputStream
& stream
, bool verbose
, int index
)
268 TIFF
*tif
= TIFFwxOpen( stream
, "image", "r" );
274 wxLogError( _("TIFF: Error loading image.") );
280 if (!TIFFSetDirectory( tif
, (tdir_t
)index
))
284 wxLogError( _("Invalid TIFF image index.") );
295 TIFFGetField( tif
, TIFFTAG_IMAGEWIDTH
, &w
);
296 TIFFGetField( tif
, TIFFTAG_IMAGELENGTH
, &h
);
300 TIFFGetFieldDefaulted(tif
, TIFFTAG_EXTRASAMPLES
,
301 &extraSamples
, &samplesInfo
);
302 const bool hasAlpha
= (extraSamples
== 1 &&
303 (samplesInfo
[0] == EXTRASAMPLE_ASSOCALPHA
||
304 samplesInfo
[0] == EXTRASAMPLE_UNASSALPHA
));
306 // guard against integer overflow during multiplication which could result
307 // in allocating a too small buffer and then overflowing it
308 const double bytesNeeded
= (double)w
* (double)h
* sizeof(uint32
);
309 if ( bytesNeeded
>= wxUINT32_MAX
)
313 wxLogError( _("TIFF: Image size is abnormally big.") );
321 raster
= (uint32
*) _TIFFmalloc( (uint32
)bytesNeeded
);
327 wxLogError( _("TIFF: Couldn't allocate memory.") );
335 image
->Create( (int)w
, (int)h
);
340 wxLogError( _("TIFF: Couldn't allocate memory.") );
352 if (!TIFFReadRGBAImage( tif
, w
, h
, raster
, 0 ))
356 wxLogError( _("TIFF: Error reading image.") );
366 unsigned char *ptr
= image
->GetData();
369 unsigned char *alpha
= hasAlpha
? image
->GetAlpha() : NULL
;
375 for (uint32 i
= 0; i
< h
; i
++)
377 for (uint32 j
= 0; j
< w
; j
++)
379 *(ptr
++) = (unsigned char)TIFFGetR(raster
[pos
]);
380 *(ptr
++) = (unsigned char)TIFFGetG(raster
[pos
]);
381 *(ptr
++) = (unsigned char)TIFFGetB(raster
[pos
]);
383 *(alpha
++) = (unsigned char)TIFFGetA(raster
[pos
]);
388 // subtract line we just added plus one line:
394 // set the image resolution if it's available
396 if ( TIFFGetField(tif
, TIFFTAG_RESOLUTIONUNIT
, &tiffRes
) )
398 wxImageResolution res
;
402 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
407 res
= wxIMAGE_RESOLUTION_NONE
;
411 res
= wxIMAGE_RESOLUTION_INCHES
;
414 case RESUNIT_CENTIMETER
:
415 res
= wxIMAGE_RESOLUTION_CM
;
419 if ( res
!= wxIMAGE_RESOLUTION_NONE
)
422 if ( TIFFGetField(tif
, TIFFTAG_XRESOLUTION
, &xres
) )
423 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONX
, wxRound(xres
));
425 if ( TIFFGetField(tif
, TIFFTAG_YRESOLUTION
, &yres
) )
426 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONY
, wxRound(yres
));
438 int wxTIFFHandler::DoGetImageCount( wxInputStream
& stream
)
440 TIFF
*tif
= TIFFwxOpen( stream
, "image", "r" );
445 int dircount
= 0; // according to the libtiff docs, dircount should be set to 1 here???
448 } while (TIFFReadDirectory(tif
));
452 // NOTE: this function modifies the current stream position but it's ok
453 // (see wxImageHandler::GetImageCount)
458 bool wxTIFFHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
460 TIFF
*tif
= TIFFwxOpen( stream
, "image", "w" );
466 wxLogError( _("TIFF: Error saving image.") );
472 TIFFSetField(tif
, TIFFTAG_ORIENTATION
, ORIENTATION_TOPLEFT
);
473 TIFFSetField(tif
, TIFFTAG_IMAGEWIDTH
, (uint32
)image
->GetWidth());
474 TIFFSetField(tif
, TIFFTAG_IMAGELENGTH
, (uint32
)image
->GetHeight());
475 TIFFSetField(tif
, TIFFTAG_ORIENTATION
, ORIENTATION_TOPLEFT
);
476 TIFFSetField(tif
, TIFFTAG_PLANARCONFIG
, PLANARCONFIG_CONTIG
);
478 // save the image resolution if we have it
480 const wxImageResolution res
= GetResolutionFromOptions(*image
, &xres
, &yres
);
485 wxFAIL_MSG( wxT("unknown image resolution units") );
488 case wxIMAGE_RESOLUTION_NONE
:
489 tiffRes
= RESUNIT_NONE
;
492 case wxIMAGE_RESOLUTION_INCHES
:
493 tiffRes
= RESUNIT_INCH
;
496 case wxIMAGE_RESOLUTION_CM
:
497 tiffRes
= RESUNIT_CENTIMETER
;
501 if ( tiffRes
!= RESUNIT_NONE
)
503 TIFFSetField(tif
, TIFFTAG_RESOLUTIONUNIT
, tiffRes
);
504 TIFFSetField(tif
, TIFFTAG_XRESOLUTION
, (float)xres
);
505 TIFFSetField(tif
, TIFFTAG_YRESOLUTION
, (float)yres
);
509 int spp
= image
->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL
);
513 int bpp
= image
->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE
);
517 int compression
= image
->GetOptionInt(wxIMAGE_OPTION_COMPRESSION
);
520 // we can't use COMPRESSION_LZW because current version of libtiff
521 // doesn't implement it ("no longer implemented due to Unisys patent
522 // enforcement") and other compression methods are lossy so we
523 // shouldn't use them by default -- and the only remaining one is none
524 compression
= COMPRESSION_NONE
;
527 TIFFSetField(tif
, TIFFTAG_SAMPLESPERPIXEL
, spp
);
528 TIFFSetField(tif
, TIFFTAG_BITSPERSAMPLE
, bpp
);
529 TIFFSetField(tif
, TIFFTAG_PHOTOMETRIC
, spp
*bpp
== 1 ? PHOTOMETRIC_MINISBLACK
531 TIFFSetField(tif
, TIFFTAG_COMPRESSION
, compression
);
533 // scanlinesize if determined by spp and bpp
534 tsize_t linebytes
= (tsize_t
)image
->GetWidth() * spp
* bpp
/ 8;
536 if ( (image
->GetWidth() % 8 > 0) && (spp
* bpp
< 8) )
541 if (TIFFScanlineSize(tif
) > linebytes
|| (spp
* bpp
< 24))
543 buf
= (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif
));
548 wxLogError( _("TIFF: Couldn't allocate memory.") );
561 TIFFSetField(tif
, TIFFTAG_ROWSPERSTRIP
,TIFFDefaultStripSize(tif
, (uint32
) -1));
563 unsigned char *ptr
= image
->GetData();
564 for ( int row
= 0; row
< image
->GetHeight(); row
++ )
571 memcpy(buf
, ptr
, image
->GetWidth());
573 else // black and white image
575 for ( int column
= 0; column
< linebytes
; column
++ )
578 for ( int bp
= 0; bp
< 8; bp
++ )
580 if ( ptr
[column
*24 + bp
*3] > 0 )
582 // check only red as this is sufficient
583 reverse
= (uint8
)(reverse
| 128 >> bp
);
587 buf
[column
] = reverse
;
592 if ( TIFFWriteScanline(tif
, buf
? buf
: ptr
, (uint32
)row
, 0) < 0 )
596 wxLogError( _("TIFF: Error writing image.") );
606 ptr
+= image
->GetWidth()*3;
609 (void) TIFFClose(tif
);
617 bool wxTIFFHandler::DoCanRead( wxInputStream
& stream
)
619 unsigned char hdr
[2];
621 if ( !stream
.Read(&hdr
[0], WXSIZEOF(hdr
)) ) // it's ok to modify the stream position here
624 return (hdr
[0] == 'I' && hdr
[1] == 'I') ||
625 (hdr
[0] == 'M' && hdr
[1] == 'M');
628 #endif // wxUSE_STREAMS
630 #endif // wxUSE_LIBTIFF