]> git.saurik.com Git - wxWidgets.git/blame - src/common/imagtiff.cpp
fix memory leak in the usage example
[wxWidgets.git] / src / common / imagtiff.cpp
CommitLineData
257bcf28 1/////////////////////////////////////////////////////////////////////////////
38d4b1e4 2// Name: src/common/imagtiff.cpp
8f493002
VS
3// Purpose: wxImage TIFF handler
4// Author: Robert Roebling
257bcf28 5// RCS-ID: $Id$
8f493002 6// Copyright: (c) Robert Roebling
65571936 7// Licence: wxWindows licence
257bcf28
RR
8/////////////////////////////////////////////////////////////////////////////
9
257bcf28
RR
10// For compilers that support precompilation, includes "wx.h".
11#include "wx/wxprec.h"
12
13#ifdef __BORLANDC__
8898456d 14 #pragma hdrstop
257bcf28
RR
15#endif
16
c96ea657 17#if wxUSE_IMAGE && wxUSE_LIBTIFF
257bcf28 18
88a7a4e1
WS
19#include "wx/imagtiff.h"
20
8898456d
WS
21#ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/app.h"
88a7a4e1 24 #include "wx/intl.h"
0bca0373 25 #include "wx/bitmap.h"
02761f6c 26 #include "wx/module.h"
8898456d
WS
27#endif
28
257bcf28
RR
29extern "C"
30{
8df068ca
CE
31#ifdef __DMC__
32 #include "tif_config.h"
33#endif
257bcf28
RR
34 #include "tiff.h"
35 #include "tiffio.h"
257bcf28
RR
36}
37#include "wx/filefn.h"
38#include "wx/wfstream.h"
257bcf28 39
0729bd19 40#ifndef TIFFLINKAGEMODE
0bca0373
WS
41 #if defined(__WATCOMC__) && defined(__WXMGL__)
42 #define TIFFLINKAGEMODE cdecl
43 #else
44 #define TIFFLINKAGEMODE LINKAGEMODE
45 #endif
19193a2c 46#endif
0729bd19 47
257bcf28
RR
48//-----------------------------------------------------------------------------
49// wxTIFFHandler
50//-----------------------------------------------------------------------------
51
257bcf28 52IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler)
257bcf28 53
e30285ab
VZ
54#if wxUSE_STREAMS
55
ec524671
VZ
56// helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
57// bit, toff_t
58static toff_t wxFileOffsetToTIFF(wxFileOffset ofs)
59{
60 if ( ofs == wxInvalidOffset )
61 return (toff_t)-1;
62
63 toff_t tofs = wx_truncate_cast(toff_t, ofs);
38d4b1e4 64 wxCHECK_MSG( (wxFileOffset)tofs == ofs, (toff_t)-1,
ec524671
VZ
65 _T("TIFF library doesn't support large files") );
66
67 return tofs;
68}
69
70// another helper to convert standard seek mode to our
71static wxSeekMode wxSeekModeFromTIFF(int whence)
72{
73 switch ( whence )
74 {
75 case SEEK_SET:
76 return wxFromStart;
77
78 case SEEK_CUR:
79 return wxFromCurrent;
80
81 case SEEK_END:
82 return wxFromEnd;
83
84 default:
85 return wxFromCurrent;
86 }
87}
88
90350682
VZ
89extern "C"
90{
91
92tsize_t TIFFLINKAGEMODE
46f36538 93wxTIFFNullProc(thandle_t WXUNUSED(handle),
19193a2c
KB
94 tdata_t WXUNUSED(buf),
95 tsize_t WXUNUSED(size))
f6bcfd97
BP
96{
97 return (tsize_t) -1;
98}
99
90350682 100tsize_t TIFFLINKAGEMODE
46f36538 101wxTIFFReadProc(thandle_t handle, tdata_t buf, tsize_t size)
257bcf28
RR
102{
103 wxInputStream *stream = (wxInputStream*) handle;
104 stream->Read( (void*) buf, (size_t) size );
4a10ea8b 105 return wx_truncate_cast(tsize_t, stream->LastRead());
257bcf28
RR
106}
107
90350682 108tsize_t TIFFLINKAGEMODE
46f36538 109wxTIFFWriteProc(thandle_t handle, tdata_t buf, tsize_t size)
257bcf28
RR
110{
111 wxOutputStream *stream = (wxOutputStream*) handle;
112 stream->Write( (void*) buf, (size_t) size );
4a10ea8b 113 return wx_truncate_cast(tsize_t, stream->LastWrite());
257bcf28
RR
114}
115
90350682 116toff_t TIFFLINKAGEMODE
46f36538 117wxTIFFSeekIProc(thandle_t handle, toff_t off, int whence)
257bcf28
RR
118{
119 wxInputStream *stream = (wxInputStream*) handle;
13111b2a 120
ec524671
VZ
121 return wxFileOffsetToTIFF(stream->SeekI((wxFileOffset)off,
122 wxSeekModeFromTIFF(whence)));
257bcf28
RR
123}
124
90350682 125toff_t TIFFLINKAGEMODE
46f36538 126wxTIFFSeekOProc(thandle_t handle, toff_t off, int whence)
f6bcfd97
BP
127{
128 wxOutputStream *stream = (wxOutputStream*) handle;
f6bcfd97 129
ec524671
VZ
130 return wxFileOffsetToTIFF(stream->SeekO((wxFileOffset)off,
131 wxSeekModeFromTIFF(whence)));
f6bcfd97
BP
132}
133
90350682 134int TIFFLINKAGEMODE
46f36538 135wxTIFFCloseIProc(thandle_t WXUNUSED(handle))
257bcf28 136{
be0d315e
VZ
137 // there is no need to close the input stream
138 return 0;
139}
140
141int TIFFLINKAGEMODE
46f36538 142wxTIFFCloseOProc(thandle_t handle)
be0d315e
VZ
143{
144 wxOutputStream *stream = (wxOutputStream*) handle;
145
146 return stream->Close() ? 0 : -1;
257bcf28
RR
147}
148
90350682 149toff_t TIFFLINKAGEMODE
46f36538 150wxTIFFSizeProc(thandle_t handle)
257bcf28 151{
f6bcfd97 152 wxStreamBase *stream = (wxStreamBase*) handle;
0b72db08 153 return (toff_t) stream->GetSize();
257bcf28
RR
154}
155
90350682 156int TIFFLINKAGEMODE
46f36538 157wxTIFFMapProc(thandle_t WXUNUSED(handle),
13111b2a
VZ
158 tdata_t* WXUNUSED(pbase),
159 toff_t* WXUNUSED(psize))
257bcf28
RR
160{
161 return 0;
162}
163
90350682 164void TIFFLINKAGEMODE
46f36538 165wxTIFFUnmapProc(thandle_t WXUNUSED(handle),
13111b2a
VZ
166 tdata_t WXUNUSED(base),
167 toff_t WXUNUSED(size))
257bcf28
RR
168{
169}
170
0fc7f695 171static void
7bea7b91
WS
172TIFFwxWarningHandler(const char* module,
173 const char* WXUNUSED_IN_UNICODE(fmt),
174 va_list WXUNUSED_IN_UNICODE(ap))
0fc7f695
JS
175{
176 if (module != NULL)
e4f0e73d
VZ
177 wxLogWarning(_("tiff module: %s"), wxString::FromAscii(module).c_str());
178
179 // FIXME: this is not terrible informative but better than crashing!
180#if wxUSE_UNICODE
181 wxLogWarning(_("TIFF library warning."));
182#else
183 wxVLogWarning(fmt, ap);
184#endif
0fc7f695 185}
7beb59f3 186
0fc7f695 187static void
7bea7b91
WS
188TIFFwxErrorHandler(const char* module,
189 const char* WXUNUSED_IN_UNICODE(fmt),
190 va_list WXUNUSED_IN_UNICODE(ap))
0fc7f695
JS
191{
192 if (module != NULL)
e4f0e73d
VZ
193 wxLogError(_("tiff module: %s"), wxString::FromAscii(module).c_str());
194
195 // FIXME: as above
196#if wxUSE_UNICODE
197 wxLogError(_("TIFF library error."));
198#else
199 wxVLogError(fmt, ap);
200#endif
0fc7f695
JS
201}
202
90350682
VZ
203} // extern "C"
204
257bcf28
RR
205TIFF*
206TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode)
207{
208 TIFF* tif = TIFFClientOpen(name, mode,
209 (thandle_t) &stream,
46f36538
VZ
210 wxTIFFReadProc, wxTIFFNullProc,
211 wxTIFFSeekIProc, wxTIFFCloseIProc, wxTIFFSizeProc,
212 wxTIFFMapProc, wxTIFFUnmapProc);
257bcf28 213
257bcf28
RR
214 return tif;
215}
216
f6bcfd97
BP
217TIFF*
218TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode)
219{
220 TIFF* tif = TIFFClientOpen(name, mode,
221 (thandle_t) &stream,
46f36538
VZ
222 wxTIFFNullProc, wxTIFFWriteProc,
223 wxTIFFSeekOProc, wxTIFFCloseOProc, wxTIFFSizeProc,
224 wxTIFFMapProc, wxTIFFUnmapProc);
f6bcfd97
BP
225
226 return tif;
227}
257bcf28 228
0fc7f695
JS
229wxTIFFHandler::wxTIFFHandler()
230{
231 m_name = wxT("TIFF file");
232 m_extension = wxT("tif");
233 m_type = wxBITMAP_TYPE_TIF;
234 m_mime = wxT("image/tiff");
235 TIFFSetWarningHandler((TIFFErrorHandler) TIFFwxWarningHandler);
236 TIFFSetErrorHandler((TIFFErrorHandler) TIFFwxErrorHandler);
237}
238
700ec454 239bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
257bcf28 240{
60d43ad8
VS
241 if (index == -1)
242 index = 0;
243
257bcf28 244 image->Destroy();
13111b2a 245
0b72db08 246 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
13111b2a 247
257bcf28
RR
248 if (!tif)
249 {
250 if (verbose)
58c837a4 251 wxLogError( _("TIFF: Error loading image.") );
13111b2a 252
7beb59f3 253 return false;
257bcf28 254 }
13111b2a 255
700ec454
RR
256 if (!TIFFSetDirectory( tif, (tdir_t)index ))
257 {
258 if (verbose)
259 wxLogError( _("Invalid TIFF image index.") );
13111b2a 260
700ec454 261 TIFFClose( tif );
13111b2a 262
7beb59f3 263 return false;
700ec454 264 }
257bcf28
RR
265
266 uint32 w, h;
13111b2a 267 uint32 npixels;
257bcf28 268 uint32 *raster;
13111b2a 269
257bcf28
RR
270 TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w );
271 TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h );
13111b2a 272
b6ac40dc
VS
273 uint16 extraSamples;
274 uint16* samplesInfo;
275 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
276 &extraSamples, &samplesInfo);
277 const bool hasAlpha = (extraSamples == 1 &&
278 (samplesInfo[0] == EXTRASAMPLE_ASSOCALPHA ||
279 samplesInfo[0] == EXTRASAMPLE_UNASSALPHA));
280
257bcf28 281 npixels = w * h;
13111b2a 282
257bcf28 283 raster = (uint32*) _TIFFmalloc( npixels * sizeof(uint32) );
13111b2a 284
257bcf28
RR
285 if (!raster)
286 {
287 if (verbose)
58c837a4 288 wxLogError( _("TIFF: Couldn't allocate memory.") );
38755449 289
f6bcfd97 290 TIFFClose( tif );
13111b2a 291
7beb59f3 292 return false;
257bcf28
RR
293 }
294
479cd5de 295 image->Create( (int)w, (int)h );
13111b2a 296 if (!image->Ok())
257bcf28
RR
297 {
298 if (verbose)
58c837a4 299 wxLogError( _("TIFF: Couldn't allocate memory.") );
13111b2a
VZ
300
301 _TIFFfree( raster );
f6bcfd97 302 TIFFClose( tif );
13111b2a 303
7beb59f3 304 return false;
257bcf28 305 }
13111b2a 306
b6ac40dc
VS
307 if ( hasAlpha )
308 image->SetAlpha();
309
257bcf28
RR
310 if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
311 {
312 if (verbose)
58c837a4 313 wxLogError( _("TIFF: Error reading image.") );
13111b2a
VZ
314
315 _TIFFfree( raster );
316 image->Destroy();
f6bcfd97 317 TIFFClose( tif );
13111b2a 318
7beb59f3 319 return false;
257bcf28 320 }
13111b2a 321
257bcf28 322 unsigned char *ptr = image->GetData();
5c5ab9eb 323 ptr += w*3*(h-1);
b6ac40dc
VS
324
325 unsigned char *alpha = hasAlpha ? image->GetAlpha() : NULL;
326 if ( hasAlpha )
327 alpha += w*(h-1);
328
257bcf28 329 uint32 pos = 0;
13111b2a 330
257bcf28
RR
331 for (uint32 i = 0; i < h; i++)
332 {
ff7c6c9c 333 for (uint32 j = 0; j < w; j++)
13111b2a 334 {
b6ac40dc
VS
335 *(ptr++) = (unsigned char)TIFFGetR(raster[pos]);
336 *(ptr++) = (unsigned char)TIFFGetG(raster[pos]);
337 *(ptr++) = (unsigned char)TIFFGetB(raster[pos]);
338 if ( hasAlpha )
339 *(alpha++) = (unsigned char)TIFFGetA(raster[pos]);
340
13111b2a
VZ
341 pos++;
342 }
b6ac40dc
VS
343
344 // subtract line we just added plus one line:
345 ptr -= 2*w*3;
346 if ( hasAlpha )
347 alpha -= 2*w;
257bcf28 348 }
13111b2a 349
37ba70a5
VZ
350 // set the image resolution if it's available
351 uint16 tiffRes;
352 if ( TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &tiffRes) )
353 {
354 wxImageResolution res;
355 switch ( tiffRes )
356 {
357 default:
358 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
359 tiffRes);
360 // fall through
361
362 case RESUNIT_NONE:
363 res = wxIMAGE_RESOLUTION_NONE;
364 break;
365
366 case RESUNIT_INCH:
367 res = wxIMAGE_RESOLUTION_INCHES;
368 break;
369
370 case RESUNIT_CENTIMETER:
371 res = wxIMAGE_RESOLUTION_CM;
372 break;
373 }
374
375 if ( res != wxIMAGE_RESOLUTION_NONE )
376 {
377 float xres, yres;
378 if ( TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) )
ad91e1ad 379 image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, wxRound(xres));
37ba70a5
VZ
380
381 if ( TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) )
ad91e1ad 382 image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, wxRound(yres));
37ba70a5
VZ
383 }
384 }
385
386
257bcf28 387 _TIFFfree( raster );
13111b2a 388
257bcf28 389 TIFFClose( tif );
13111b2a 390
7beb59f3 391 return true;
257bcf28
RR
392}
393
649d13e8 394int wxTIFFHandler::GetImageCount( wxInputStream& stream )
700ec454
RR
395{
396 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
13111b2a 397
700ec454 398 if (!tif)
13111b2a 399 return 0;
257bcf28 400
700ec454
RR
401 int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here???
402 do {
403 dircount++;
404 } while (TIFFReadDirectory(tif));
13111b2a 405
700ec454 406 TIFFClose( tif );
13111b2a 407
700ec454
RR
408 return dircount;
409}
257bcf28 410
f6bcfd97 411bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
257bcf28 412{
f6bcfd97
BP
413 TIFF *tif = TIFFwxOpen( stream, "image", "w" );
414
415 if (!tif)
416 {
417 if (verbose)
418 wxLogError( _("TIFF: Error saving image.") );
419
7beb59f3 420 return false;
f6bcfd97
BP
421 }
422
fe9308c6 423 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
f6bcfd97
BP
424 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32)image->GetWidth());
425 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight());
426 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
f6bcfd97 427 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
38755449 428
37ba70a5
VZ
429 // save the image resolution if we have it
430 int xres, yres;
431 const wxImageResolution res = GetResolutionFromOptions(*image, &xres, &yres);
432 uint16 tiffRes;
433 switch ( res )
fe9308c6 434 {
37ba70a5
VZ
435 default:
436 wxFAIL_MSG( _T("unknown image resolution units") );
437 // fall through
438
439 case wxIMAGE_RESOLUTION_NONE:
440 tiffRes = RESUNIT_NONE;
441 break;
442
443 case wxIMAGE_RESOLUTION_INCHES:
444 tiffRes = RESUNIT_INCH;
445 break;
446
447 case wxIMAGE_RESOLUTION_CM:
448 tiffRes = RESUNIT_CENTIMETER;
449 break;
fe9308c6
VZ
450 }
451
37ba70a5
VZ
452 if ( tiffRes != RESUNIT_NONE )
453 {
454 TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, tiffRes);
455 TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres);
456 TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres);
457 }
458
459
fe9308c6
VZ
460 int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
461 if ( !spp )
462 spp = 3;
463
464 int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
465 if ( !bpp )
37ba70a5 466 bpp = 8;
fe9308c6
VZ
467
468 int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
469 if ( !compression )
f5e20985
VZ
470 {
471 // we can't use COMPRESSION_LZW because current version of libtiff
472 // doesn't implement it ("no longer implemented due to Unisys patent
473 // enforcement") and other compression methods are lossy so we
474 // shouldn't use them by default -- and the only remaining one is none
475 compression = COMPRESSION_NONE;
476 }
fe9308c6
VZ
477
478 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
479 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
480 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
481 : PHOTOMETRIC_RGB);
482 TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);
483
484 // scanlinesize if determined by spp and bpp
485 tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;
486
487 if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
488 linebytes+=1;
489
f6bcfd97 490 unsigned char *buf;
38755449 491
fe9308c6 492 if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
f6bcfd97
BP
493 {
494 buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
495 if (!buf)
496 {
497 if (verbose)
498 wxLogError( _("TIFF: Couldn't allocate memory.") );
499
500 TIFFClose( tif );
501
7beb59f3 502 return false;
f6bcfd97 503 }
38755449
DW
504 }
505 else
f6bcfd97
BP
506 {
507 buf = NULL;
508 }
509
fe9308c6
VZ
510 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));
511
f6bcfd97 512 unsigned char *ptr = image->GetData();
fe9308c6 513 for ( int row = 0; row < image->GetHeight(); row++ )
f6bcfd97 514 {
fe9308c6
VZ
515 if ( buf )
516 {
517 if ( spp * bpp > 1 )
518 {
519 // color image
520 memcpy(buf, ptr, image->GetWidth());
521 }
522 else // black and white image
523 {
524 for ( int column = 0; column < linebytes; column++ )
525 {
526 uint8 reverse = 0;
fe9308c6
VZ
527 for ( int bp = 0; bp < 8; bp++ )
528 {
529 if ( ptr[column*24 + bp*3] > 0 )
530 {
531 // check only red as this is sufficient
38d4b1e4 532 reverse = (uint8)(reverse | 128 >> bp);
fe9308c6 533 }
fe9308c6
VZ
534 }
535
3ba9ea72 536 buf[column] = reverse;
fe9308c6
VZ
537 }
538 }
539 }
38755449 540
fe9308c6 541 if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
f6bcfd97 542 {
19193a2c
KB
543 if (verbose)
544 wxLogError( _("TIFF: Error writing image.") );
38755449 545
f6bcfd97
BP
546 TIFFClose( tif );
547 if (buf)
548 _TIFFfree(buf);
38755449 549
7beb59f3 550 return false;
f6bcfd97 551 }
fe9308c6 552
f6bcfd97
BP
553 ptr += image->GetWidth()*3;
554 }
555
556 (void) TIFFClose(tif);
557
558 if (buf)
fe9308c6 559 _TIFFfree(buf);
f6bcfd97 560
7beb59f3 561 return true;
257bcf28
RR
562}
563
564bool wxTIFFHandler::DoCanRead( wxInputStream& stream )
565{
0b72db08 566 unsigned char hdr[2];
257bcf28 567
7ac31c42 568 if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) )
7beb59f3 569 return false;
79fa2374 570
79fa2374
VZ
571 return (hdr[0] == 'I' && hdr[1] == 'I') ||
572 (hdr[0] == 'M' && hdr[1] == 'M');
257bcf28
RR
573}
574
e30285ab 575#endif // wxUSE_STREAMS
257bcf28 576
e30285ab 577#endif // wxUSE_LIBTIFF