]> git.saurik.com Git - wxWidgets.git/blob - src/common/imagtiff.cpp
fix bugs introduced in wxCmdLineParser::ConvertStringToArgs() during Unicode transiti...
[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
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 #endif
36
37 extern "C"
38 {
39 #ifdef __DMC__
40 #include "tif_config.h"
41 #endif
42 #include "tiff.h"
43 #include "tiffio.h"
44 }
45 #include "wx/filefn.h"
46 #include "wx/wfstream.h"
47
48 #ifndef TIFFLINKAGEMODE
49 #if defined(__WATCOMC__) && defined(__WXMGL__)
50 #define TIFFLINKAGEMODE cdecl
51 #else
52 #define TIFFLINKAGEMODE LINKAGEMODE
53 #endif
54 #endif
55
56 // ============================================================================
57 // implementation
58 // ============================================================================
59
60 // ----------------------------------------------------------------------------
61 // TIFF library error/warning handlers
62 // ----------------------------------------------------------------------------
63
64 extern "C"
65 {
66
67 static void
68 TIFFwxWarningHandler(const char* module,
69 const char* WXUNUSED_IN_UNICODE(fmt),
70 va_list WXUNUSED_IN_UNICODE(ap))
71 {
72 if (module != NULL)
73 wxLogWarning(_("tiff module: %s"), wxString::FromAscii(module).c_str());
74
75 // FIXME: this is not terrible informative but better than crashing!
76 #if wxUSE_UNICODE
77 wxLogWarning(_("TIFF library warning."));
78 #else
79 wxVLogWarning(fmt, ap);
80 #endif
81 }
82
83 static void
84 TIFFwxErrorHandler(const char* module,
85 const char* WXUNUSED_IN_UNICODE(fmt),
86 va_list WXUNUSED_IN_UNICODE(ap))
87 {
88 if (module != NULL)
89 wxLogError(_("tiff module: %s"), wxString::FromAscii(module).c_str());
90
91 // FIXME: as above
92 #if wxUSE_UNICODE
93 wxLogError(_("TIFF library error."));
94 #else
95 wxVLogError(fmt, ap);
96 #endif
97 }
98
99 } // extern "C"
100
101 //-----------------------------------------------------------------------------
102 // wxTIFFHandler
103 //-----------------------------------------------------------------------------
104
105 IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler)
106
107 wxTIFFHandler::wxTIFFHandler()
108 {
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);
115 }
116
117 #if wxUSE_STREAMS
118
119 // helper to translate our, possibly 64 bit, wxFileOffset to TIFF, always 32
120 // bit, toff_t
121 static toff_t wxFileOffsetToTIFF(wxFileOffset ofs)
122 {
123 if ( ofs == wxInvalidOffset )
124 return (toff_t)-1;
125
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") );
129
130 return tofs;
131 }
132
133 // another helper to convert standard seek mode to our
134 static wxSeekMode wxSeekModeFromTIFF(int whence)
135 {
136 switch ( whence )
137 {
138 case SEEK_SET:
139 return wxFromStart;
140
141 case SEEK_CUR:
142 return wxFromCurrent;
143
144 case SEEK_END:
145 return wxFromEnd;
146
147 default:
148 return wxFromCurrent;
149 }
150 }
151
152 extern "C"
153 {
154
155 tsize_t TIFFLINKAGEMODE
156 wxTIFFNullProc(thandle_t WXUNUSED(handle),
157 tdata_t WXUNUSED(buf),
158 tsize_t WXUNUSED(size))
159 {
160 return (tsize_t) -1;
161 }
162
163 tsize_t TIFFLINKAGEMODE
164 wxTIFFReadProc(thandle_t handle, tdata_t buf, tsize_t size)
165 {
166 wxInputStream *stream = (wxInputStream*) handle;
167 stream->Read( (void*) buf, (size_t) size );
168 return wx_truncate_cast(tsize_t, stream->LastRead());
169 }
170
171 tsize_t TIFFLINKAGEMODE
172 wxTIFFWriteProc(thandle_t handle, tdata_t buf, tsize_t size)
173 {
174 wxOutputStream *stream = (wxOutputStream*) handle;
175 stream->Write( (void*) buf, (size_t) size );
176 return wx_truncate_cast(tsize_t, stream->LastWrite());
177 }
178
179 toff_t TIFFLINKAGEMODE
180 wxTIFFSeekIProc(thandle_t handle, toff_t off, int whence)
181 {
182 wxInputStream *stream = (wxInputStream*) handle;
183
184 return wxFileOffsetToTIFF(stream->SeekI((wxFileOffset)off,
185 wxSeekModeFromTIFF(whence)));
186 }
187
188 toff_t TIFFLINKAGEMODE
189 wxTIFFSeekOProc(thandle_t handle, toff_t off, int whence)
190 {
191 wxOutputStream *stream = (wxOutputStream*) handle;
192
193 return wxFileOffsetToTIFF(stream->SeekO((wxFileOffset)off,
194 wxSeekModeFromTIFF(whence)));
195 }
196
197 int TIFFLINKAGEMODE
198 wxTIFFCloseIProc(thandle_t WXUNUSED(handle))
199 {
200 // there is no need to close the input stream
201 return 0;
202 }
203
204 int TIFFLINKAGEMODE
205 wxTIFFCloseOProc(thandle_t handle)
206 {
207 wxOutputStream *stream = (wxOutputStream*) handle;
208
209 return stream->Close() ? 0 : -1;
210 }
211
212 toff_t TIFFLINKAGEMODE
213 wxTIFFSizeProc(thandle_t handle)
214 {
215 wxStreamBase *stream = (wxStreamBase*) handle;
216 return (toff_t) stream->GetSize();
217 }
218
219 int TIFFLINKAGEMODE
220 wxTIFFMapProc(thandle_t WXUNUSED(handle),
221 tdata_t* WXUNUSED(pbase),
222 toff_t* WXUNUSED(psize))
223 {
224 return 0;
225 }
226
227 void TIFFLINKAGEMODE
228 wxTIFFUnmapProc(thandle_t WXUNUSED(handle),
229 tdata_t WXUNUSED(base),
230 toff_t WXUNUSED(size))
231 {
232 }
233
234 } // extern "C"
235
236 TIFF*
237 TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode)
238 {
239 TIFF* tif = TIFFClientOpen(name, mode,
240 (thandle_t) &stream,
241 wxTIFFReadProc, wxTIFFNullProc,
242 wxTIFFSeekIProc, wxTIFFCloseIProc, wxTIFFSizeProc,
243 wxTIFFMapProc, wxTIFFUnmapProc);
244
245 return tif;
246 }
247
248 TIFF*
249 TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode)
250 {
251 TIFF* tif = TIFFClientOpen(name, mode,
252 (thandle_t) &stream,
253 wxTIFFNullProc, wxTIFFWriteProc,
254 wxTIFFSeekOProc, wxTIFFCloseOProc, wxTIFFSizeProc,
255 wxTIFFMapProc, wxTIFFUnmapProc);
256
257 return tif;
258 }
259
260 bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
261 {
262 if (index == -1)
263 index = 0;
264
265 image->Destroy();
266
267 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
268
269 if (!tif)
270 {
271 if (verbose)
272 wxLogError( _("TIFF: Error loading image.") );
273
274 return false;
275 }
276
277 if (!TIFFSetDirectory( tif, (tdir_t)index ))
278 {
279 if (verbose)
280 wxLogError( _("Invalid TIFF image index.") );
281
282 TIFFClose( tif );
283
284 return false;
285 }
286
287 uint32 w, h;
288 uint32 npixels;
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 npixels = w * h;
303
304 raster = (uint32*) _TIFFmalloc( npixels * sizeof(uint32) );
305
306 if (!raster)
307 {
308 if (verbose)
309 wxLogError( _("TIFF: Couldn't allocate memory.") );
310
311 TIFFClose( tif );
312
313 return false;
314 }
315
316 image->Create( (int)w, (int)h );
317 if (!image->Ok())
318 {
319 if (verbose)
320 wxLogError( _("TIFF: Couldn't allocate memory.") );
321
322 _TIFFfree( raster );
323 TIFFClose( tif );
324
325 return false;
326 }
327
328 if ( hasAlpha )
329 image->SetAlpha();
330
331 if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
332 {
333 if (verbose)
334 wxLogError( _("TIFF: Error reading image.") );
335
336 _TIFFfree( raster );
337 image->Destroy();
338 TIFFClose( tif );
339
340 return false;
341 }
342
343 unsigned char *ptr = image->GetData();
344 ptr += w*3*(h-1);
345
346 unsigned char *alpha = hasAlpha ? image->GetAlpha() : NULL;
347 if ( hasAlpha )
348 alpha += w*(h-1);
349
350 uint32 pos = 0;
351
352 for (uint32 i = 0; i < h; i++)
353 {
354 for (uint32 j = 0; j < w; j++)
355 {
356 *(ptr++) = (unsigned char)TIFFGetR(raster[pos]);
357 *(ptr++) = (unsigned char)TIFFGetG(raster[pos]);
358 *(ptr++) = (unsigned char)TIFFGetB(raster[pos]);
359 if ( hasAlpha )
360 *(alpha++) = (unsigned char)TIFFGetA(raster[pos]);
361
362 pos++;
363 }
364
365 // subtract line we just added plus one line:
366 ptr -= 2*w*3;
367 if ( hasAlpha )
368 alpha -= 2*w;
369 }
370
371 // set the image resolution if it's available
372 uint16 tiffRes;
373 if ( TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &tiffRes) )
374 {
375 wxImageResolution res;
376 switch ( tiffRes )
377 {
378 default:
379 wxLogWarning(_("Unknown TIFF resolution unit %d ignored"),
380 tiffRes);
381 // fall through
382
383 case RESUNIT_NONE:
384 res = wxIMAGE_RESOLUTION_NONE;
385 break;
386
387 case RESUNIT_INCH:
388 res = wxIMAGE_RESOLUTION_INCHES;
389 break;
390
391 case RESUNIT_CENTIMETER:
392 res = wxIMAGE_RESOLUTION_CM;
393 break;
394 }
395
396 if ( res != wxIMAGE_RESOLUTION_NONE )
397 {
398 float xres, yres;
399 if ( TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) )
400 image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, wxRound(xres));
401
402 if ( TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) )
403 image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, wxRound(yres));
404 }
405 }
406
407
408 _TIFFfree( raster );
409
410 TIFFClose( tif );
411
412 return true;
413 }
414
415 int wxTIFFHandler::GetImageCount( wxInputStream& stream )
416 {
417 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
418
419 if (!tif)
420 return 0;
421
422 int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here???
423 do {
424 dircount++;
425 } while (TIFFReadDirectory(tif));
426
427 TIFFClose( tif );
428
429 return dircount;
430 }
431
432 bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
433 {
434 TIFF *tif = TIFFwxOpen( stream, "image", "w" );
435
436 if (!tif)
437 {
438 if (verbose)
439 wxLogError( _("TIFF: Error saving image.") );
440
441 return false;
442 }
443
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);
449
450 // save the image resolution if we have it
451 int xres, yres;
452 const wxImageResolution res = GetResolutionFromOptions(*image, &xres, &yres);
453 uint16 tiffRes;
454 switch ( res )
455 {
456 default:
457 wxFAIL_MSG( _T("unknown image resolution units") );
458 // fall through
459
460 case wxIMAGE_RESOLUTION_NONE:
461 tiffRes = RESUNIT_NONE;
462 break;
463
464 case wxIMAGE_RESOLUTION_INCHES:
465 tiffRes = RESUNIT_INCH;
466 break;
467
468 case wxIMAGE_RESOLUTION_CM:
469 tiffRes = RESUNIT_CENTIMETER;
470 break;
471 }
472
473 if ( tiffRes != RESUNIT_NONE )
474 {
475 TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, tiffRes);
476 TIFFSetField(tif, TIFFTAG_XRESOLUTION, (float)xres);
477 TIFFSetField(tif, TIFFTAG_YRESOLUTION, (float)yres);
478 }
479
480
481 int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
482 if ( !spp )
483 spp = 3;
484
485 int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
486 if ( !bpp )
487 bpp = 8;
488
489 int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
490 if ( !compression )
491 {
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;
497 }
498
499 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
500 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
501 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
502 : PHOTOMETRIC_RGB);
503 TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);
504
505 // scanlinesize if determined by spp and bpp
506 tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;
507
508 if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
509 linebytes+=1;
510
511 unsigned char *buf;
512
513 if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
514 {
515 buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
516 if (!buf)
517 {
518 if (verbose)
519 wxLogError( _("TIFF: Couldn't allocate memory.") );
520
521 TIFFClose( tif );
522
523 return false;
524 }
525 }
526 else
527 {
528 buf = NULL;
529 }
530
531 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));
532
533 unsigned char *ptr = image->GetData();
534 for ( int row = 0; row < image->GetHeight(); row++ )
535 {
536 if ( buf )
537 {
538 if ( spp * bpp > 1 )
539 {
540 // color image
541 memcpy(buf, ptr, image->GetWidth());
542 }
543 else // black and white image
544 {
545 for ( int column = 0; column < linebytes; column++ )
546 {
547 uint8 reverse = 0;
548 for ( int bp = 0; bp < 8; bp++ )
549 {
550 if ( ptr[column*24 + bp*3] > 0 )
551 {
552 // check only red as this is sufficient
553 reverse = (uint8)(reverse | 128 >> bp);
554 }
555 }
556
557 buf[column] = reverse;
558 }
559 }
560 }
561
562 if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
563 {
564 if (verbose)
565 wxLogError( _("TIFF: Error writing image.") );
566
567 TIFFClose( tif );
568 if (buf)
569 _TIFFfree(buf);
570
571 return false;
572 }
573
574 ptr += image->GetWidth()*3;
575 }
576
577 (void) TIFFClose(tif);
578
579 if (buf)
580 _TIFFfree(buf);
581
582 return true;
583 }
584
585 bool wxTIFFHandler::DoCanRead( wxInputStream& stream )
586 {
587 unsigned char hdr[2];
588
589 if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) )
590 return false;
591
592 return (hdr[0] == 'I' && hdr[1] == 'I') ||
593 (hdr[0] == 'M' && hdr[1] == 'M');
594 }
595
596 #endif // wxUSE_STREAMS
597
598 #endif // wxUSE_LIBTIFF