Improved saving of TIFF monochrome images.
[wxWidgets.git] / src / common / imagtiff.cpp
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 #include "wx/versioninfo.h"
29
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #include "wx/intl.h"
34 #include "wx/bitmap.h"
35 #include "wx/module.h"
36 #include "wx/wxcrtvararg.h"
37 #endif
38
39 extern "C"
40 {
41 #ifdef __DMC__
42 #include "tif_config.h"
43 #endif
44 #include "tiff.h"
45 #include "tiffio.h"
46 }
47 #include "wx/filefn.h"
48 #include "wx/wfstream.h"
49
50 #ifndef TIFFLINKAGEMODE
51 #if defined(__WATCOMC__) && defined(__WXMGL__)
52 #define TIFFLINKAGEMODE cdecl
53 #else
54 #define TIFFLINKAGEMODE LINKAGEMODE
55 #endif
56 #endif
57
58 // ============================================================================
59 // implementation
60 // ============================================================================
61
62 // ----------------------------------------------------------------------------
63 // TIFF library error/warning handlers
64 // ----------------------------------------------------------------------------
65
66 static wxString
67 FormatTiffMessage(const char *module, const char *fmt, va_list ap)
68 {
69 char buf[512];
70 if ( wxCRT_VsnprintfA(buf, WXSIZEOF(buf), fmt, ap) <= 0 )
71 {
72 // this isn't supposed to happen, but if it does, it's better
73 // than nothing
74 strcpy(buf, "Incorrectly formatted TIFF message");
75 }
76 buf[WXSIZEOF(buf)-1] = 0; // make sure it is always NULL-terminated
77
78 wxString msg(buf);
79 if ( module )
80 msg += wxString::Format(_(" (in module \"%s\")"), module);
81
82 return msg;
83 }
84
85 extern "C"
86 {
87
88 static void
89 TIFFwxWarningHandler(const char* module, const char *fmt, va_list ap)
90 {
91 wxLogWarning("%s", FormatTiffMessage(module, fmt, ap));
92 }
93
94 static void
95 TIFFwxErrorHandler(const char* module, const char *fmt, va_list ap)
96 {
97 wxLogError("%s", FormatTiffMessage(module, fmt, ap));
98 }
99
100 } // extern "C"
101
102 //-----------------------------------------------------------------------------
103 // wxTIFFHandler
104 //-----------------------------------------------------------------------------
105
106 IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler)
107
108 wxTIFFHandler::wxTIFFHandler()
109 {
110 m_name = wxT("TIFF file");
111 m_extension = wxT("tif");
112 m_altExtensions.Add(wxT("tiff"));
113 m_type = wxBITMAP_TYPE_TIF;
114 m_mime = wxT("image/tiff");
115 TIFFSetWarningHandler((TIFFErrorHandler) TIFFwxWarningHandler);
116 TIFFSetErrorHandler((TIFFErrorHandler) TIFFwxErrorHandler);
117 }
118
119 #if wxUSE_STREAMS
120
121 // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
122 // bit, toff_t
123 static toff_t wxFileOffsetToTIFF(wxFileOffset ofs)
124 {
125 if ( ofs == wxInvalidOffset )
126 return (toff_t)-1;
127
128 toff_t tofs = wx_truncate_cast(toff_t, ofs);
129 wxCHECK_MSG( (wxFileOffset)tofs == ofs, (toff_t)-1,
130 wxT("TIFF library doesn't support large files") );
131
132 return tofs;
133 }
134
135 // another helper to convert standard seek mode to our
136 static wxSeekMode wxSeekModeFromTIFF(int whence)
137 {
138 switch ( whence )
139 {
140 case SEEK_SET:
141 return wxFromStart;
142
143 case SEEK_CUR:
144 return wxFromCurrent;
145
146 case SEEK_END:
147 return wxFromEnd;
148
149 default:
150 return wxFromCurrent;
151 }
152 }
153
154 extern "C"
155 {
156
157 tsize_t TIFFLINKAGEMODE
158 wxTIFFNullProc(thandle_t WXUNUSED(handle),
159 tdata_t WXUNUSED(buf),
160 tsize_t WXUNUSED(size))
161 {
162 return (tsize_t) -1;
163 }
164
165 tsize_t TIFFLINKAGEMODE
166 wxTIFFReadProc(thandle_t handle, tdata_t buf, tsize_t size)
167 {
168 wxInputStream *stream = (wxInputStream*) handle;
169 stream->Read( (void*) buf, (size_t) size );
170 return wx_truncate_cast(tsize_t, stream->LastRead());
171 }
172
173 tsize_t TIFFLINKAGEMODE
174 wxTIFFWriteProc(thandle_t handle, tdata_t buf, tsize_t size)
175 {
176 wxOutputStream *stream = (wxOutputStream*) handle;
177 stream->Write( (void*) buf, (size_t) size );
178 return wx_truncate_cast(tsize_t, stream->LastWrite());
179 }
180
181 toff_t TIFFLINKAGEMODE
182 wxTIFFSeekIProc(thandle_t handle, toff_t off, int whence)
183 {
184 wxInputStream *stream = (wxInputStream*) handle;
185
186 return wxFileOffsetToTIFF(stream->SeekI((wxFileOffset)off,
187 wxSeekModeFromTIFF(whence)));
188 }
189
190 toff_t TIFFLINKAGEMODE
191 wxTIFFSeekOProc(thandle_t handle, toff_t off, int whence)
192 {
193 wxOutputStream *stream = (wxOutputStream*) handle;
194
195 toff_t offset = wxFileOffsetToTIFF(
196 stream->SeekO((wxFileOffset)off, wxSeekModeFromTIFF(whence)) );
197
198 if (offset != (toff_t) -1 || whence != SEEK_SET)
199 {
200 return offset;
201 }
202
203
204 /*
205 Try to workaround problems with libtiff seeking past the end of streams.
206
207 This occurs when libtiff is writing tag entries past the end of a
208 stream but hasn't written the directory yet (which will be placed
209 before the tags and contain offsets to the just written tags).
210 The behaviour for seeking past the end of a stream is not consistent
211 and doesn't work with for example wxMemoryOutputStream. When this type
212 of seeking fails (with SEEK_SET), fill in the gap with zeroes and try
213 again.
214 */
215
216 wxFileOffset streamLength = stream->GetLength();
217 if (streamLength != wxInvalidOffset && (wxFileOffset) off > streamLength)
218 {
219 if (stream->SeekO(streamLength, wxFromStart) == wxInvalidOffset)
220 {
221 return (toff_t) -1;
222 }
223
224 for (wxFileOffset i = 0; i < (wxFileOffset) off - streamLength; ++i)
225 {
226 stream->PutC(0);
227 }
228 }
229
230 return wxFileOffsetToTIFF( stream->TellO() );
231 }
232
233 int TIFFLINKAGEMODE
234 wxTIFFCloseIProc(thandle_t WXUNUSED(handle))
235 {
236 // there is no need to close the input stream
237 return 0;
238 }
239
240 int TIFFLINKAGEMODE
241 wxTIFFCloseOProc(thandle_t handle)
242 {
243 wxOutputStream *stream = (wxOutputStream*) handle;
244
245 return stream->Close() ? 0 : -1;
246 }
247
248 toff_t TIFFLINKAGEMODE
249 wxTIFFSizeProc(thandle_t handle)
250 {
251 wxStreamBase *stream = (wxStreamBase*) handle;
252 return (toff_t) stream->GetSize();
253 }
254
255 int TIFFLINKAGEMODE
256 wxTIFFMapProc(thandle_t WXUNUSED(handle),
257 tdata_t* WXUNUSED(pbase),
258 toff_t* WXUNUSED(psize))
259 {
260 return 0;
261 }
262
263 void TIFFLINKAGEMODE
264 wxTIFFUnmapProc(thandle_t WXUNUSED(handle),
265 tdata_t WXUNUSED(base),
266 toff_t WXUNUSED(size))
267 {
268 }
269
270 } // extern "C"
271
272 TIFF*
273 TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode)
274 {
275 TIFF* tif = TIFFClientOpen(name, mode,
276 (thandle_t) &stream,
277 wxTIFFReadProc, wxTIFFNullProc,
278 wxTIFFSeekIProc, wxTIFFCloseIProc, wxTIFFSizeProc,
279 wxTIFFMapProc, wxTIFFUnmapProc);
280
281 return tif;
282 }
283
284 TIFF*
285 TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode)
286 {
287 TIFF* tif = TIFFClientOpen(name, mode,
288 (thandle_t) &stream,
289 wxTIFFNullProc, wxTIFFWriteProc,
290 wxTIFFSeekOProc, wxTIFFCloseOProc, wxTIFFSizeProc,
291 wxTIFFMapProc, wxTIFFUnmapProc);
292
293 return tif;
294 }
295
296 bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
297 {
298 if (index == -1)
299 index = 0;
300
301 image->Destroy();
302
303 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
304
305 if (!tif)
306 {
307 if (verbose)
308 {
309 wxLogError( _("TIFF: Error loading image.") );
310 }
311
312 return false;
313 }
314
315 if (!TIFFSetDirectory( tif, (tdir_t)index ))
316 {
317 if (verbose)
318 {
319 wxLogError( _("Invalid TIFF image index.") );
320 }
321
322 TIFFClose( tif );
323
324 return false;
325 }
326
327 uint32 w, h;
328 uint32 *raster;
329
330 TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w );
331 TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h );
332
333 uint16 photometric;
334 uint16 samplesPerPixel;
335 uint16 extraSamples;
336 uint16* samplesInfo;
337 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel);
338 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES,
339 &extraSamples, &samplesInfo);
340 if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
341 {
342 photometric = PHOTOMETRIC_MINISWHITE;
343 }
344 const bool hasAlpha = (extraSamples >= 1
345 && ((samplesInfo[0] == EXTRASAMPLE_UNSPECIFIED && samplesPerPixel > 3)
346 || samplesInfo[0] == EXTRASAMPLE_ASSOCALPHA
347 || samplesInfo[0] == EXTRASAMPLE_UNASSALPHA))
348 || (extraSamples == 0 && samplesPerPixel == 4
349 && photometric == PHOTOMETRIC_RGB);
350
351 // guard against integer overflow during multiplication which could result
352 // in allocating a too small buffer and then overflowing it
353 const double bytesNeeded = (double)w * (double)h * sizeof(uint32);
354 if ( bytesNeeded >= wxUINT32_MAX )
355 {
356 if ( verbose )
357 {
358 wxLogError( _("TIFF: Image size is abnormally big.") );
359 }
360
361 TIFFClose(tif);
362
363 return false;
364 }
365
366 raster = (uint32*) _TIFFmalloc( (uint32)bytesNeeded );
367
368 if (!raster)
369 {
370 if (verbose)
371 {
372 wxLogError( _("TIFF: Couldn't allocate memory.") );
373 }
374
375 TIFFClose( tif );
376
377 return false;
378 }
379
380 image->Create( (int)w, (int)h );
381 if (!image->IsOk())
382 {
383 if (verbose)
384 {
385 wxLogError( _("TIFF: Couldn't allocate memory.") );
386 }
387
388 _TIFFfree( raster );
389 TIFFClose( tif );
390
391 return false;
392 }
393
394 if ( hasAlpha )
395 image->SetAlpha();
396
397 if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
398 {
399 if (verbose)
400 {
401 wxLogError( _("TIFF: Error reading image.") );
402 }
403
404 _TIFFfree( raster );
405 image->Destroy();
406 TIFFClose( tif );
407
408 return false;
409 }
410
411 unsigned char *ptr = image->GetData();
412 ptr += w*3*(h-1);
413
414 unsigned char *alpha = hasAlpha ? image->GetAlpha() : NULL;
415 if ( hasAlpha )
416 alpha += w*(h-1);
417
418 uint32 pos = 0;
419
420 for (uint32 i = 0; i < h; i++)
421 {
422 for (uint32 j = 0; j < w; j++)
423 {
424 *(ptr++) = (unsigned char)TIFFGetR(raster[pos]);
425 *(ptr++) = (unsigned char)TIFFGetG(raster[pos]);
426 *(ptr++) = (unsigned char)TIFFGetB(raster[pos]);
427 if ( hasAlpha )
428 *(alpha++) = (unsigned char)TIFFGetA(raster[pos]);
429
430 pos++;
431 }
432
433 // subtract line we just added plus one line:
434 ptr -= 2*w*3;
435 if ( hasAlpha )
436 alpha -= 2*w;
437 }
438
439
440 uint16 spp, bpp, compression;
441 /*
442 Read some baseline TIFF tags which helps when re-saving a TIFF
443 to be similar to the original image.
444 */
445 if ( TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp) )
446 {
447 image->SetOption(wxIMAGE_OPTION_SAMPLESPERPIXEL, spp);
448 }
449
450 if ( TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bpp) )
451 {
452 image->SetOption(wxIMAGE_OPTION_BITSPERSAMPLE, bpp);
453 }
454
455 if ( TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compression) )
456 {
457 image->SetOption(wxIMAGE_OPTION_COMPRESSION, compression);
458 }
459
460 // Set the resolution unit.
461 wxImageResolution resUnit = wxIMAGE_RESOLUTION_NONE;
462 uint16 tiffRes;
463 if ( TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &tiffRes) )
464 {
465 switch (tiffRes)
466 {
467 default:
468 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
469 tiffRes);
470 // fall through
471
472 case RESUNIT_NONE:
473 resUnit = wxIMAGE_RESOLUTION_NONE;
474 break;
475
476 case RESUNIT_INCH:
477 resUnit = wxIMAGE_RESOLUTION_INCHES;
478 break;
479
480 case RESUNIT_CENTIMETER:
481 resUnit = wxIMAGE_RESOLUTION_CM;
482 break;
483 }
484 }
485
486 image->SetOption(wxIMAGE_OPTION_RESOLUTIONUNIT, resUnit);
487
488 /*
489 Set the image resolution if it's available. Resolution tag is not
490 dependant on RESOLUTIONUNIT != RESUNIT_NONE (according to TIFF spec).
491 */
492 float resX, resY;
493
494 if ( TIFFGetField(tif, TIFFTAG_XRESOLUTION, &resX) )
495 {
496 /*
497 Use a string value to not lose precision.
498 rounding to int as cm and then converting to inch may
499 result in whole integer rounding error, eg. 201 instead of 200 dpi.
500 If an app wants an int, GetOptionInt will convert and round down.
501 */
502 image->SetOption(wxIMAGE_OPTION_RESOLUTIONX,
503 wxString::FromCDouble((double) resX));
504 }
505
506 if ( TIFFGetField(tif, TIFFTAG_YRESOLUTION, &resY) )
507 {
508 image->SetOption(wxIMAGE_OPTION_RESOLUTIONY,
509 wxString::FromCDouble((double) resY));
510 }
511
512 _TIFFfree( raster );
513
514 TIFFClose( tif );
515
516 return true;
517 }
518
519 int wxTIFFHandler::DoGetImageCount( wxInputStream& stream )
520 {
521 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
522
523 if (!tif)
524 return 0;
525
526 int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here???
527 do {
528 dircount++;
529 } while (TIFFReadDirectory(tif));
530
531 TIFFClose( tif );
532
533 // NOTE: this function modifies the current stream position but it's ok
534 // (see wxImageHandler::GetImageCount)
535
536 return dircount;
537 }
538
539 bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
540 {
541 TIFF *tif = TIFFwxOpen( stream, "image", "w" );
542
543 if (!tif)
544 {
545 if (verbose)
546 {
547 wxLogError( _("TIFF: Error saving image.") );
548 }
549
550 return false;
551 }
552
553 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
554 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32)image->GetWidth());
555 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight());
556 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
557 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
558
559 // save the image resolution if we have it
560 int xres, yres;
561 const wxImageResolution res = GetResolutionFromOptions(*image, &xres, &yres);
562 uint16 tiffRes;
563 switch ( res )
564 {
565 default:
566 wxFAIL_MSG( wxT("unknown image resolution units") );
567 // fall through
568
569 case wxIMAGE_RESOLUTION_NONE:
570 tiffRes = RESUNIT_NONE;
571 break;
572
573 case wxIMAGE_RESOLUTION_INCHES:
574 tiffRes = RESUNIT_INCH;
575 break;
576
577 case wxIMAGE_RESOLUTION_CM:
578 tiffRes = RESUNIT_CENTIMETER;
579 break;
580 }
581
582 if ( tiffRes != RESUNIT_NONE )
583 {
584 TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, tiffRes);
585 TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres);
586 TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres);
587 }
588
589
590 int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
591 if ( !spp )
592 spp = 3;
593
594 int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
595 if ( !bpp )
596 bpp = 8;
597
598 int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
599 if ( !compression )
600 {
601 // we can't use COMPRESSION_LZW because current version of libtiff
602 // doesn't implement it ("no longer implemented due to Unisys patent
603 // enforcement") and other compression methods are lossy so we
604 // shouldn't use them by default -- and the only remaining one is none
605 compression = COMPRESSION_NONE;
606 }
607
608 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
609 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
610 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
611 : PHOTOMETRIC_RGB);
612 TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);
613
614 // scanlinesize if determined by spp and bpp
615 tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;
616
617 if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
618 linebytes+=1;
619
620 unsigned char *buf;
621
622 if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
623 {
624 buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
625 if (!buf)
626 {
627 if (verbose)
628 {
629 wxLogError( _("TIFF: Couldn't allocate memory.") );
630 }
631
632 TIFFClose( tif );
633
634 return false;
635 }
636 }
637 else
638 {
639 buf = NULL;
640 }
641
642 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));
643
644 unsigned char *ptr = image->GetData();
645 for ( int row = 0; row < image->GetHeight(); row++ )
646 {
647 if ( buf )
648 {
649 if ( spp * bpp > 1 )
650 {
651 // color image
652 memcpy(buf, ptr, image->GetWidth());
653 }
654 else // black and white image
655 {
656 for ( int column = 0; column < linebytes; column++ )
657 {
658 uint8 reverse = 0;
659 for ( int bp = 0; bp < 8; bp++ )
660 {
661 if ( ptr[column*24 + bp*3] > 127 )
662 {
663 // check only red as this is sufficient
664 reverse = (uint8)(reverse | 128 >> bp);
665 }
666 }
667
668 buf[column] = reverse;
669 }
670 }
671 }
672
673 if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
674 {
675 if (verbose)
676 {
677 wxLogError( _("TIFF: Error writing image.") );
678 }
679
680 TIFFClose( tif );
681 if (buf)
682 _TIFFfree(buf);
683
684 return false;
685 }
686
687 ptr += image->GetWidth()*3;
688 }
689
690 (void) TIFFClose(tif);
691
692 if (buf)
693 _TIFFfree(buf);
694
695 return true;
696 }
697
698 bool wxTIFFHandler::DoCanRead( wxInputStream& stream )
699 {
700 unsigned char hdr[2];
701
702 if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) ) // it's ok to modify the stream position here
703 return false;
704
705 return (hdr[0] == 'I' && hdr[1] == 'I') ||
706 (hdr[0] == 'M' && hdr[1] == 'M');
707 }
708
709 #endif // wxUSE_STREAMS
710
711 /*static*/ wxVersionInfo wxTIFFHandler::GetLibraryVersionInfo()
712 {
713 int major,
714 minor,
715 micro;
716
717 const wxString ver(::TIFFGetVersion());
718 if ( wxSscanf(ver, "LIBTIFF, Version %d.%d.%d", &major, &minor, &micro) != 3 )
719 {
720 wxLogDebug("Unrecognized libtiff version string \"%s\"", ver);
721
722 major =
723 minor =
724 micro = 0;
725 }
726
727 wxString copyright;
728 const wxString desc = ver.BeforeFirst('\n', &copyright);
729 copyright.Replace("\n", "");
730
731 return wxVersionInfo("libtiff", major, minor, micro, desc, copyright);
732 }
733
734 #endif // wxUSE_LIBTIFF