at least not crash in case of TIFF warnings/errors in Unicode build (but we still...
[wxWidgets.git] / src / common / imagtiff.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
11 #pragma implementation "imagtiff.h"
12 #endif
13
14 // For compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
16
17 #ifdef __BORLANDC__
18 #pragma hdrstop
19 #endif
20
21 #include "wx/defs.h"
22
23 #if wxUSE_IMAGE && wxUSE_LIBTIFF
24
25 #include "wx/imagtiff.h"
26 #include "wx/bitmap.h"
27 #include "wx/debug.h"
28 #include "wx/log.h"
29 #include "wx/app.h"
30 extern "C"
31 {
32 #include "tiff.h"
33 #include "tiffio.h"
34 }
35 #include "wx/filefn.h"
36 #include "wx/wfstream.h"
37 #include "wx/intl.h"
38 #include "wx/module.h"
39
40 #ifndef TIFFLINKAGEMODE
41 #define TIFFLINKAGEMODE LINKAGEMODE
42 #endif
43
44 //-----------------------------------------------------------------------------
45 // wxTIFFHandler
46 //-----------------------------------------------------------------------------
47
48 IMPLEMENT_DYNAMIC_CLASS(wxTIFFHandler,wxImageHandler)
49
50 #if wxUSE_STREAMS
51
52 extern "C"
53 {
54
55 tsize_t TIFFLINKAGEMODE
56 _tiffNullProc(thandle_t WXUNUSED(handle),
57 tdata_t WXUNUSED(buf),
58 tsize_t WXUNUSED(size))
59 {
60 return (tsize_t) -1;
61 }
62
63 tsize_t TIFFLINKAGEMODE
64 _tiffReadProc(thandle_t handle, tdata_t buf, tsize_t size)
65 {
66 wxInputStream *stream = (wxInputStream*) handle;
67 stream->Read( (void*) buf, (size_t) size );
68 return stream->LastRead();
69 }
70
71 tsize_t TIFFLINKAGEMODE
72 _tiffWriteProc(thandle_t handle, tdata_t buf, tsize_t size)
73 {
74 wxOutputStream *stream = (wxOutputStream*) handle;
75 stream->Write( (void*) buf, (size_t) size );
76 return stream->LastWrite();
77 }
78
79 toff_t TIFFLINKAGEMODE
80 _tiffSeekIProc(thandle_t handle, toff_t off, int whence)
81 {
82 wxInputStream *stream = (wxInputStream*) handle;
83 wxSeekMode mode;
84 switch (whence)
85 {
86 case SEEK_SET: mode = wxFromStart; break;
87 case SEEK_CUR: mode = wxFromCurrent; break;
88 case SEEK_END: mode = wxFromEnd; break;
89 default: mode = wxFromCurrent; break;
90 }
91
92 return (toff_t)stream->SeekI( (wxFileOffset)off, mode );
93 }
94
95 toff_t TIFFLINKAGEMODE
96 _tiffSeekOProc(thandle_t handle, toff_t off, int whence)
97 {
98 wxOutputStream *stream = (wxOutputStream*) handle;
99 wxSeekMode mode;
100 switch (whence)
101 {
102 case SEEK_SET: mode = wxFromStart; break;
103 case SEEK_CUR: mode = wxFromCurrent; break;
104 case SEEK_END: mode = wxFromEnd; break;
105 default: mode = wxFromCurrent; break;
106 }
107
108 return (toff_t)stream->SeekO( (wxFileOffset)off, mode );
109 }
110
111 int TIFFLINKAGEMODE
112 _tiffCloseProc(thandle_t WXUNUSED(handle))
113 {
114 return 0; // ?
115 }
116
117 toff_t TIFFLINKAGEMODE
118 _tiffSizeProc(thandle_t handle)
119 {
120 wxStreamBase *stream = (wxStreamBase*) handle;
121 return (toff_t) stream->GetSize();
122 }
123
124 int TIFFLINKAGEMODE
125 _tiffMapProc(thandle_t WXUNUSED(handle),
126 tdata_t* WXUNUSED(pbase),
127 toff_t* WXUNUSED(psize))
128 {
129 return 0;
130 }
131
132 void TIFFLINKAGEMODE
133 _tiffUnmapProc(thandle_t WXUNUSED(handle),
134 tdata_t WXUNUSED(base),
135 toff_t WXUNUSED(size))
136 {
137 }
138
139 static void
140 TIFFwxWarningHandler(const char* module, const char* fmt, va_list ap)
141 {
142 if (module != NULL)
143 wxLogWarning(_("tiff module: %s"), wxString::FromAscii(module).c_str());
144
145 // FIXME: this is not terrible informative but better than crashing!
146 #if wxUSE_UNICODE
147 wxLogWarning(_("TIFF library warning."));
148 #else
149 wxVLogWarning(fmt, ap);
150 #endif
151 }
152
153 static void
154 TIFFwxErrorHandler(const char* module, const char* fmt, va_list ap)
155 {
156 if (module != NULL)
157 wxLogError(_("tiff module: %s"), wxString::FromAscii(module).c_str());
158
159 // FIXME: as above
160 #if wxUSE_UNICODE
161 wxLogError(_("TIFF library error."));
162 #else
163 wxVLogError(fmt, ap);
164 #endif
165 }
166
167 } // extern "C"
168
169 TIFF*
170 TIFFwxOpen(wxInputStream &stream, const char* name, const char* mode)
171 {
172 TIFF* tif = TIFFClientOpen(name, mode,
173 (thandle_t) &stream,
174 _tiffReadProc, _tiffNullProc,
175 _tiffSeekIProc, _tiffCloseProc, _tiffSizeProc,
176 _tiffMapProc, _tiffUnmapProc);
177
178 return tif;
179 }
180
181 TIFF*
182 TIFFwxOpen(wxOutputStream &stream, const char* name, const char* mode)
183 {
184 TIFF* tif = TIFFClientOpen(name, mode,
185 (thandle_t) &stream,
186 _tiffNullProc, _tiffWriteProc,
187 _tiffSeekOProc, _tiffCloseProc, _tiffSizeProc,
188 _tiffMapProc, _tiffUnmapProc);
189
190 return tif;
191 }
192
193 wxTIFFHandler::wxTIFFHandler()
194 {
195 m_name = wxT("TIFF file");
196 m_extension = wxT("tif");
197 m_type = wxBITMAP_TYPE_TIF;
198 m_mime = wxT("image/tiff");
199 TIFFSetWarningHandler((TIFFErrorHandler) TIFFwxWarningHandler);
200 TIFFSetErrorHandler((TIFFErrorHandler) TIFFwxErrorHandler);
201 }
202
203 bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
204 {
205 if (index == -1)
206 index = 0;
207
208 image->Destroy();
209
210 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
211
212 if (!tif)
213 {
214 if (verbose)
215 wxLogError( _("TIFF: Error loading image.") );
216
217 return false;
218 }
219
220 if (!TIFFSetDirectory( tif, (tdir_t)index ))
221 {
222 if (verbose)
223 wxLogError( _("Invalid TIFF image index.") );
224
225 TIFFClose( tif );
226
227 return false;
228 }
229
230 uint32 w, h;
231 uint32 npixels;
232 uint32 *raster;
233
234 TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w );
235 TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h );
236
237 npixels = w * h;
238
239 raster = (uint32*) _TIFFmalloc( npixels * sizeof(uint32) );
240
241 if (!raster)
242 {
243 if (verbose)
244 wxLogError( _("TIFF: Couldn't allocate memory.") );
245
246 TIFFClose( tif );
247
248 return false;
249 }
250
251 image->Create( (int)w, (int)h );
252 if (!image->Ok())
253 {
254 if (verbose)
255 wxLogError( _("TIFF: Couldn't allocate memory.") );
256
257 _TIFFfree( raster );
258 TIFFClose( tif );
259
260 return false;
261 }
262
263 if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
264 {
265 if (verbose)
266 wxLogError( _("TIFF: Error reading image.") );
267
268 _TIFFfree( raster );
269 image->Destroy();
270 TIFFClose( tif );
271
272 return false;
273 }
274
275 bool hasmask = false;
276
277 unsigned char *ptr = image->GetData();
278 ptr += w*3*(h-1);
279 uint32 pos = 0;
280
281 for (uint32 i = 0; i < h; i++)
282 {
283 for (uint32 j = 0; j < w; j++)
284 {
285 unsigned char alpha = (unsigned char)TIFFGetA(raster[pos]);
286 if (alpha < 127)
287 {
288 hasmask = true;
289 ptr[0] = image->GetMaskRed();
290 ptr++;
291 ptr[0] = image->GetMaskGreen();
292 ptr++;
293 ptr[0] = image->GetMaskBlue();
294 ptr++;
295 }
296 else
297 {
298 ptr[0] = (unsigned char)TIFFGetR(raster[pos]);
299 ptr++;
300 ptr[0] = (unsigned char)TIFFGetG(raster[pos]);
301 ptr++;
302 ptr[0] = (unsigned char)TIFFGetB(raster[pos]);
303 ptr++;
304 }
305 pos++;
306 }
307 ptr -= 2*w*3; // subtract line we just added plus one line
308 }
309
310 _TIFFfree( raster );
311
312 TIFFClose( tif );
313
314 image->SetMask( hasmask );
315
316 return true;
317 }
318
319 int wxTIFFHandler::GetImageCount( wxInputStream& stream )
320 {
321 TIFF *tif = TIFFwxOpen( stream, "image", "r" );
322
323 if (!tif)
324 return 0;
325
326 int dircount = 0; // according to the libtiff docs, dircount should be set to 1 here???
327 do {
328 dircount++;
329 } while (TIFFReadDirectory(tif));
330
331 TIFFClose( tif );
332
333 return dircount;
334 }
335
336 bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
337 {
338 TIFF *tif = TIFFwxOpen( stream, "image", "w" );
339
340 if (!tif)
341 {
342 if (verbose)
343 wxLogError( _("TIFF: Error saving image.") );
344
345 return false;
346 }
347
348 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
349 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (uint32)image->GetWidth());
350 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight());
351 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
352 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
353
354 if ( image->HasOption(wxIMAGE_OPTION_RESOLUTIONX) &&
355 image->HasOption(wxIMAGE_OPTION_RESOLUTIONY) )
356 {
357 TIFFSetField(tif, TIFFTAG_XRESOLUTION,
358 (float)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX));
359 TIFFSetField(tif, TIFFTAG_YRESOLUTION,
360 (float)image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY));
361 }
362
363 int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
364 if ( !spp )
365 spp = 3;
366
367 int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
368 if ( !bpp )
369 bpp=8;
370
371 int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
372 if ( !compression )
373 compression=COMPRESSION_LZW;
374
375 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
376 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
377 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
378 : PHOTOMETRIC_RGB);
379 TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);
380
381 // scanlinesize if determined by spp and bpp
382 tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;
383
384 if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
385 linebytes+=1;
386
387 unsigned char *buf;
388
389 if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
390 {
391 buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
392 if (!buf)
393 {
394 if (verbose)
395 wxLogError( _("TIFF: Couldn't allocate memory.") );
396
397 TIFFClose( tif );
398
399 return false;
400 }
401 }
402 else
403 {
404 buf = NULL;
405 }
406
407 TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));
408
409 unsigned char *ptr = image->GetData();
410 for ( int row = 0; row < image->GetHeight(); row++ )
411 {
412 if ( buf )
413 {
414 if ( spp * bpp > 1 )
415 {
416 // color image
417 memcpy(buf, ptr, image->GetWidth());
418 }
419 else // black and white image
420 {
421 for ( int column = 0; column < linebytes; column++ )
422 {
423 uint8 reverse = 0;
424 for ( int bp = 0; bp < 8; bp++ )
425 {
426 if ( ptr[column*24 + bp*3] > 0 )
427 {
428 // check only red as this is sufficient
429 reverse = reverse | 128 >> bp;
430 }
431 }
432
433 buf[column] = reverse;
434 }
435 }
436 }
437
438 if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
439 {
440 if (verbose)
441 wxLogError( _("TIFF: Error writing image.") );
442
443 TIFFClose( tif );
444 if (buf)
445 _TIFFfree(buf);
446
447 return false;
448 }
449
450 ptr += image->GetWidth()*3;
451 }
452
453 (void) TIFFClose(tif);
454
455 if (buf)
456 _TIFFfree(buf);
457
458 return true;
459 }
460
461 bool wxTIFFHandler::DoCanRead( wxInputStream& stream )
462 {
463 unsigned char hdr[2];
464
465 if ( !stream.Read(&hdr[0], WXSIZEOF(hdr)) )
466 return false;
467
468 return (hdr[0] == 'I' && hdr[1] == 'I') ||
469 (hdr[0] == 'M' && hdr[1] == 'M');
470 }
471
472 #endif // wxUSE_STREAMS
473
474 #endif // wxUSE_LIBTIFF
475