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