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_type
= wxBITMAP_TYPE_TIF
;
112 m_mime
= wxT("image/tiff");
113 TIFFSetWarningHandler((TIFFErrorHandler
) TIFFwxWarningHandler
);
114 TIFFSetErrorHandler((TIFFErrorHandler
) TIFFwxErrorHandler
);
119 // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
121 static toff_t
wxFileOffsetToTIFF(wxFileOffset ofs
)
123 if ( ofs
== wxInvalidOffset
)
126 toff_t tofs
= wx_truncate_cast(toff_t
, ofs
);
127 wxCHECK_MSG( (wxFileOffset
)tofs
== ofs
, (toff_t
)-1,
128 _T("TIFF library doesn't support large files") );
133 // another helper to convert standard seek mode to our
134 static wxSeekMode
wxSeekModeFromTIFF(int whence
)
142 return wxFromCurrent
;
148 return wxFromCurrent
;
155 tsize_t TIFFLINKAGEMODE
156 wxTIFFNullProc(thandle_t
WXUNUSED(handle
),
157 tdata_t
WXUNUSED(buf
),
158 tsize_t
WXUNUSED(size
))
163 tsize_t TIFFLINKAGEMODE
164 wxTIFFReadProc(thandle_t handle
, tdata_t buf
, tsize_t size
)
166 wxInputStream
*stream
= (wxInputStream
*) handle
;
167 stream
->Read( (void*) buf
, (size_t) size
);
168 return wx_truncate_cast(tsize_t
, stream
->LastRead());
171 tsize_t TIFFLINKAGEMODE
172 wxTIFFWriteProc(thandle_t handle
, tdata_t buf
, tsize_t size
)
174 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
175 stream
->Write( (void*) buf
, (size_t) size
);
176 return wx_truncate_cast(tsize_t
, stream
->LastWrite());
179 toff_t TIFFLINKAGEMODE
180 wxTIFFSeekIProc(thandle_t handle
, toff_t off
, int whence
)
182 wxInputStream
*stream
= (wxInputStream
*) handle
;
184 return wxFileOffsetToTIFF(stream
->SeekI((wxFileOffset
)off
,
185 wxSeekModeFromTIFF(whence
)));
188 toff_t TIFFLINKAGEMODE
189 wxTIFFSeekOProc(thandle_t handle
, toff_t off
, int whence
)
191 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
193 return wxFileOffsetToTIFF(stream
->SeekO((wxFileOffset
)off
,
194 wxSeekModeFromTIFF(whence
)));
198 wxTIFFCloseIProc(thandle_t
WXUNUSED(handle
))
200 // there is no need to close the input stream
205 wxTIFFCloseOProc(thandle_t handle
)
207 wxOutputStream
*stream
= (wxOutputStream
*) handle
;
209 return stream
->Close() ? 0 : -1;
212 toff_t TIFFLINKAGEMODE
213 wxTIFFSizeProc(thandle_t handle
)
215 wxStreamBase
*stream
= (wxStreamBase
*) handle
;
216 return (toff_t
) stream
->GetSize();
220 wxTIFFMapProc(thandle_t
WXUNUSED(handle
),
221 tdata_t
* WXUNUSED(pbase
),
222 toff_t
* WXUNUSED(psize
))
228 wxTIFFUnmapProc(thandle_t
WXUNUSED(handle
),
229 tdata_t
WXUNUSED(base
),
230 toff_t
WXUNUSED(size
))
237 TIFFwxOpen(wxInputStream
&stream
, const char* name
, const char* mode
)
239 TIFF
* tif
= TIFFClientOpen(name
, mode
,
241 wxTIFFReadProc
, wxTIFFNullProc
,
242 wxTIFFSeekIProc
, wxTIFFCloseIProc
, wxTIFFSizeProc
,
243 wxTIFFMapProc
, wxTIFFUnmapProc
);
249 TIFFwxOpen(wxOutputStream
&stream
, const char* name
, const char* mode
)
251 TIFF
* tif
= TIFFClientOpen(name
, mode
,
253 wxTIFFNullProc
, wxTIFFWriteProc
,
254 wxTIFFSeekOProc
, wxTIFFCloseOProc
, wxTIFFSizeProc
,
255 wxTIFFMapProc
, wxTIFFUnmapProc
);
260 bool wxTIFFHandler::LoadFile( wxImage
*image
, wxInputStream
& stream
, bool verbose
, int index
)
267 TIFF
*tif
= TIFFwxOpen( stream
, "image", "r" );
272 wxLogError( _("TIFF: Error loading image.") );
277 if (!TIFFSetDirectory( tif
, (tdir_t
)index
))
280 wxLogError( _("Invalid TIFF image index.") );
291 TIFFGetField( tif
, TIFFTAG_IMAGEWIDTH
, &w
);
292 TIFFGetField( tif
, TIFFTAG_IMAGELENGTH
, &h
);
296 TIFFGetFieldDefaulted(tif
, TIFFTAG_EXTRASAMPLES
,
297 &extraSamples
, &samplesInfo
);
298 const bool hasAlpha
= (extraSamples
== 1 &&
299 (samplesInfo
[0] == EXTRASAMPLE_ASSOCALPHA
||
300 samplesInfo
[0] == EXTRASAMPLE_UNASSALPHA
));
304 raster
= (uint32
*) _TIFFmalloc( npixels
* sizeof(uint32
) );
309 wxLogError( _("TIFF: Couldn't allocate memory.") );
316 image
->Create( (int)w
, (int)h
);
320 wxLogError( _("TIFF: Couldn't allocate memory.") );
331 if (!TIFFReadRGBAImage( tif
, w
, h
, raster
, 0 ))
334 wxLogError( _("TIFF: Error reading image.") );
343 unsigned char *ptr
= image
->GetData();
346 unsigned char *alpha
= hasAlpha
? image
->GetAlpha() : NULL
;
352 for (uint32 i
= 0; i
< h
; i
++)
354 for (uint32 j
= 0; j
< w
; j
++)
356 *(ptr
++) = (unsigned char)TIFFGetR(raster
[pos
]);
357 *(ptr
++) = (unsigned char)TIFFGetG(raster
[pos
]);
358 *(ptr
++) = (unsigned char)TIFFGetB(raster
[pos
]);
360 *(alpha
++) = (unsigned char)TIFFGetA(raster
[pos
]);
365 // subtract line we just added plus one line:
371 // set the image resolution if it's available
373 if ( TIFFGetField(tif
, TIFFTAG_RESOLUTIONUNIT
, &tiffRes
) )
375 wxImageResolution res
;
379 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
384 res
= wxIMAGE_RESOLUTION_NONE
;
388 res
= wxIMAGE_RESOLUTION_INCHES
;
391 case RESUNIT_CENTIMETER
:
392 res
= wxIMAGE_RESOLUTION_CM
;
396 if ( res
!= wxIMAGE_RESOLUTION_NONE
)
399 if ( TIFFGetField(tif
, TIFFTAG_XRESOLUTION
, &xres
) )
400 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONX
, wxRound(xres
));
402 if ( TIFFGetField(tif
, TIFFTAG_YRESOLUTION
, &yres
) )
403 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONY
, wxRound(yres
));
415 int wxTIFFHandler::GetImageCount( wxInputStream
& stream
)
417 TIFF
*tif
= TIFFwxOpen( stream
, "image", "r" );
422 int dircount
= 0; // according to the libtiff docs, dircount should be set to 1 here???
425 } while (TIFFReadDirectory(tif
));
432 bool wxTIFFHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
434 TIFF
*tif
= TIFFwxOpen( stream
, "image", "w" );
439 wxLogError( _("TIFF: Error saving image.") );
444 TIFFSetField(tif
, TIFFTAG_ORIENTATION
, ORIENTATION_TOPLEFT
);
445 TIFFSetField(tif
, TIFFTAG_IMAGEWIDTH
, (uint32
)image
->GetWidth());
446 TIFFSetField(tif
, TIFFTAG_IMAGELENGTH
, (uint32
)image
->GetHeight());
447 TIFFSetField(tif
, TIFFTAG_ORIENTATION
, ORIENTATION_TOPLEFT
);
448 TIFFSetField(tif
, TIFFTAG_PLANARCONFIG
, PLANARCONFIG_CONTIG
);
450 // save the image resolution if we have it
452 const wxImageResolution res
= GetResolutionFromOptions(*image
, &xres
, &yres
);
457 wxFAIL_MSG( _T("unknown image resolution units") );
460 case wxIMAGE_RESOLUTION_NONE
:
461 tiffRes
= RESUNIT_NONE
;
464 case wxIMAGE_RESOLUTION_INCHES
:
465 tiffRes
= RESUNIT_INCH
;
468 case wxIMAGE_RESOLUTION_CM
:
469 tiffRes
= RESUNIT_CENTIMETER
;
473 if ( tiffRes
!= RESUNIT_NONE
)
475 TIFFSetField(tif
, TIFFTAG_RESOLUTIONUNIT
, tiffRes
);
476 TIFFSetField(tif
, TIFFTAG_XRESOLUTION
, (float)xres
);
477 TIFFSetField(tif
, TIFFTAG_YRESOLUTION
, (float)yres
);
481 int spp
= image
->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL
);
485 int bpp
= image
->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE
);
489 int compression
= image
->GetOptionInt(wxIMAGE_OPTION_COMPRESSION
);
492 // we can't use COMPRESSION_LZW because current version of libtiff
493 // doesn't implement it ("no longer implemented due to Unisys patent
494 // enforcement") and other compression methods are lossy so we
495 // shouldn't use them by default -- and the only remaining one is none
496 compression
= COMPRESSION_NONE
;
499 TIFFSetField(tif
, TIFFTAG_SAMPLESPERPIXEL
, spp
);
500 TIFFSetField(tif
, TIFFTAG_BITSPERSAMPLE
, bpp
);
501 TIFFSetField(tif
, TIFFTAG_PHOTOMETRIC
, spp
*bpp
== 1 ? PHOTOMETRIC_MINISBLACK
503 TIFFSetField(tif
, TIFFTAG_COMPRESSION
, compression
);
505 // scanlinesize if determined by spp and bpp
506 tsize_t linebytes
= (tsize_t
)image
->GetWidth() * spp
* bpp
/ 8;
508 if ( (image
->GetWidth() % 8 > 0) && (spp
* bpp
< 8) )
513 if (TIFFScanlineSize(tif
) > linebytes
|| (spp
* bpp
< 24))
515 buf
= (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif
));
519 wxLogError( _("TIFF: Couldn't allocate memory.") );
531 TIFFSetField(tif
, TIFFTAG_ROWSPERSTRIP
,TIFFDefaultStripSize(tif
, (uint32
) -1));
533 unsigned char *ptr
= image
->GetData();
534 for ( int row
= 0; row
< image
->GetHeight(); row
++ )
541 memcpy(buf
, ptr
, image
->GetWidth());
543 else // black and white image
545 for ( int column
= 0; column
< linebytes
; column
++ )
548 for ( int bp
= 0; bp
< 8; bp
++ )
550 if ( ptr
[column
*24 + bp
*3] > 0 )
552 // check only red as this is sufficient
553 reverse
= (uint8
)(reverse
| 128 >> bp
);
557 buf
[column
] = reverse
;
562 if ( TIFFWriteScanline(tif
, buf
? buf
: ptr
, (uint32
)row
, 0) < 0 )
565 wxLogError( _("TIFF: Error writing image.") );
574 ptr
+= image
->GetWidth()*3;
577 (void) TIFFClose(tif
);
585 bool wxTIFFHandler::DoCanRead( wxInputStream
& stream
)
587 unsigned char hdr
[2];
589 if ( !stream
.Read(&hdr
[0], WXSIZEOF(hdr
)) )
592 return (hdr
[0] == 'I' && hdr
[1] == 'I') ||
593 (hdr
[0] == 'M' && hdr
[1] == 'M');
596 #endif // wxUSE_STREAMS
598 #endif // wxUSE_LIBTIFF