]> granicus.if.org Git - imagemagick/blob - coders/tiff.c
(no commit message)
[imagemagick] / coders / tiff.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                        TTTTT  IIIII  FFFFF  FFFFF                           %
7 %                          T      I    F      F                               %
8 %                          T      I    FFF    FFF                             %
9 %                          T      I    F      F                               %
10 %                          T    IIIII  F      F                               %
11 %                                                                             %
12 %                                                                             %
13 %                        Read/Write TIFF Image Format                         %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/color.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colorspace.h"
51 #include "MagickCore/colorspace-private.h"
52 #include "MagickCore/constitute.h"
53 #include "MagickCore/enhance.h"
54 #include "MagickCore/exception.h"
55 #include "MagickCore/exception-private.h"
56 #include "MagickCore/geometry.h"
57 #include "MagickCore/image.h"
58 #include "MagickCore/image-private.h"
59 #include "MagickCore/list.h"
60 #include "MagickCore/log.h"
61 #include "MagickCore/magick.h"
62 #include "MagickCore/memory_.h"
63 #include "MagickCore/module.h"
64 #include "MagickCore/monitor.h"
65 #include "MagickCore/monitor-private.h"
66 #include "MagickCore/option.h"
67 #include "MagickCore/pixel-accessor.h"
68 #include "MagickCore/property.h"
69 #include "MagickCore/quantum.h"
70 #include "MagickCore/quantum-private.h"
71 #include "MagickCore/profile.h"
72 #include "MagickCore/resize.h"
73 #include "MagickCore/resource_.h"
74 #include "MagickCore/semaphore.h"
75 #include "MagickCore/splay-tree.h"
76 #include "MagickCore/static.h"
77 #include "MagickCore/statistic.h"
78 #include "MagickCore/string_.h"
79 #include "MagickCore/string-private.h"
80 #include "MagickCore/thread_.h"
81 #include "MagickCore/utility.h"
82 #if defined(MAGICKCORE_TIFF_DELEGATE)
83 # if defined(MAGICKCORE_HAVE_TIFFCONF_H)
84 #  include "tiffconf.h"
85 # endif
86 # include "tiff.h"
87 # include "tiffio.h"
88 # if !defined(COMPRESSION_ADOBE_DEFLATE)
89 #  define COMPRESSION_ADOBE_DEFLATE  8
90 # endif
91 # if !defined(PREDICTOR_HORIZONTAL)
92 # define PREDICTOR_HORIZONTAL  2
93 # endif
94 \f
95 /*
96   Typedef declarations.
97 */
98 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
99 typedef struct _ExifInfo
100 {
101   unsigned int
102     tag,
103     type;
104
105   const char
106     *property;
107 } ExifInfo;
108
109 static const ExifInfo
110   exif_info[] = {
111     { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, "exif:ExposureTime" },
112     { EXIFTAG_FNUMBER, TIFF_RATIONAL, "exif:FNumber" },
113     { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, "exif:ExposureProgram" },
114     { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, "exif:SpectralSensitivity" },
115     { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, "exif:ISOSpeedRatings" },
116     { EXIFTAG_OECF, TIFF_UNDEFINED, "exif:OptoelectricConversionFactor" },
117     { EXIFTAG_EXIFVERSION, TIFF_UNDEFINED, "exif:ExifVersion" },
118     { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, "exif:DateTimeOriginal" },
119     { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, "exif:DateTimeDigitized" },
120     { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_UNDEFINED, "exif:ComponentsConfiguration" },
121     { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, "exif:CompressedBitsPerPixel" },
122     { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, "exif:ShutterSpeedValue" },
123     { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, "exif:ApertureValue" },
124     { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, "exif:BrightnessValue" },
125     { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, "exif:ExposureBiasValue" },
126     { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, "exif:MaxApertureValue" },
127     { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, "exif:SubjectDistance" },
128     { EXIFTAG_METERINGMODE, TIFF_SHORT, "exif:MeteringMode" },
129     { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, "exif:LightSource" },
130     { EXIFTAG_FLASH, TIFF_SHORT, "exif:Flash" },
131     { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, "exif:FocalLength" },
132     /* { EXIFTAG_SUBJECTAREA, TIFF_SHORT, "exif:SubjectArea" }, */
133     { EXIFTAG_MAKERNOTE, TIFF_UNDEFINED, "exif:MakerNote" },
134     { EXIFTAG_USERCOMMENT, TIFF_UNDEFINED, "exif:UserComment" },
135     { EXIFTAG_SUBSECTIME, TIFF_ASCII, "exif:SubSecTime" },
136     { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, "exif:SubSecTimeOriginal" },
137     { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, "exif:SubSecTimeDigitized" },
138     { EXIFTAG_FLASHPIXVERSION, TIFF_UNDEFINED, "exif:FlashpixVersion" },
139     { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, "exif:PixelXDimension" },
140     { EXIFTAG_PIXELXDIMENSION, TIFF_SHORT, "exif:PixelXDimension" },
141     { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, "exif:PixelYDimension" },
142     { EXIFTAG_PIXELYDIMENSION, TIFF_SHORT, "exif:PixelYDimension" },
143     { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, "exif:RelatedSoundFile" },
144     { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, "exif:FlashEnergy" },
145     { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_UNDEFINED, "exif:SpatialFrequencyResponse" },
146     { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneXResolution" },
147     { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneYResolution" },
148     { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, "exif:FocalPlaneResolutionUnit" },
149     { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, "exif:SubjectLocation" },
150     { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, "exif:ExposureIndex" },
151     { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, "exif:SensingMethod" },
152     { EXIFTAG_FILESOURCE, TIFF_UNDEFINED, "exif:FileSource" },
153     { EXIFTAG_SCENETYPE, TIFF_UNDEFINED, "exif:SceneType" },
154     { EXIFTAG_CFAPATTERN, TIFF_UNDEFINED, "exif:CFAPattern" },
155     { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, "exif:CustomRendered" },
156     { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, "exif:ExposureMode" },
157     { EXIFTAG_WHITEBALANCE, TIFF_SHORT, "exif:WhiteBalance" },
158     { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, "exif:DigitalZoomRatio" },
159     { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, "exif:FocalLengthIn35mmFilm" },
160     { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, "exif:SceneCaptureType" },
161     { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, "exif:GainControl" },
162     { EXIFTAG_CONTRAST, TIFF_SHORT, "exif:Contrast" },
163     { EXIFTAG_SATURATION, TIFF_SHORT, "exif:Saturation" },
164     { EXIFTAG_SHARPNESS, TIFF_SHORT, "exif:Sharpness" },
165     { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_UNDEFINED, "exif:DeviceSettingDescription" },
166     { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, "exif:SubjectDistanceRange" },
167     { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, "exif:ImageUniqueID" },
168     { 0, 0, (char *) NULL }
169 };
170 #endif
171 #endif  /* MAGICKCORE_TIFF_DELEGATE */
172 \f
173 /*
174   Global declarations.
175 */
176 static MagickThreadKey
177   tiff_exception;
178
179 static SemaphoreInfo
180   *tiff_semaphore = (SemaphoreInfo *) NULL;
181
182 static volatile MagickBooleanType
183   instantiate_key = MagickFalse;
184 \f
185 /*
186   Forward declarations.
187 */
188 #if defined(MAGICKCORE_TIFF_DELEGATE)
189 static Image *
190   ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
191
192 static MagickBooleanType
193   WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
194   WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
195   WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
196 #endif
197 \f
198 /*
199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
200 %                                                                             %
201 %                                                                             %
202 %                                                                             %
203 %   I s T I F F                                                               %
204 %                                                                             %
205 %                                                                             %
206 %                                                                             %
207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
208 %
209 %  IsTIFF() returns MagickTrue if the image format type, identified by the
210 %  magick string, is TIFF.
211 %
212 %  The format of the IsTIFF method is:
213 %
214 %      MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
215 %
216 %  A description of each parameter follows:
217 %
218 %    o magick: compare image format pattern against these bytes.
219 %
220 %    o length: Specifies the length of the magick string.
221 %
222 */
223 static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
224 {
225   if (length < 4)
226     return(MagickFalse);
227   if (memcmp(magick,"\115\115\000\052",4) == 0)
228     return(MagickTrue);
229   if (memcmp(magick,"\111\111\052\000",4) == 0)
230     return(MagickTrue);
231 #if defined(TIFF_VERSION_BIG)
232   if (length < 8)
233     return(MagickFalse);
234   if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
235     return(MagickTrue);
236   if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
237     return(MagickTrue);
238 #endif
239   return(MagickFalse);
240 }
241 \f
242 #if defined(MAGICKCORE_TIFF_DELEGATE)
243 /*
244 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
245 %                                                                             %
246 %                                                                             %
247 %                                                                             %
248 %   R e a d G R O U P 4 I m a g e                                             %
249 %                                                                             %
250 %                                                                             %
251 %                                                                             %
252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
253 %
254 %  ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it.  It
255 %  allocates the memory necessary for the new Image structure and returns a
256 %  pointer to the new image.
257 %
258 %  The format of the ReadGROUP4Image method is:
259 %
260 %      Image *ReadGROUP4Image(const ImageInfo *image_info,
261 %        ExceptionInfo *exception)
262 %
263 %  A description of each parameter follows:
264 %
265 %    o image_info: the image info.
266 %
267 %    o exception: return any errors or warnings in this structure.
268 %
269 */
270
271 static inline size_t WriteLSBLong(FILE *file,const size_t value)
272 {
273   unsigned char
274     buffer[4];
275
276   buffer[0]=(unsigned char) value;
277   buffer[1]=(unsigned char) (value >> 8);
278   buffer[2]=(unsigned char) (value >> 16);
279   buffer[3]=(unsigned char) (value >> 24);
280   return(fwrite(buffer,1,4,file));
281 }
282
283 static Image *ReadGROUP4Image(const ImageInfo *image_info,
284   ExceptionInfo *exception)
285 {
286   char
287     filename[MaxTextExtent];
288
289   FILE
290     *file;
291
292   Image
293     *image;
294
295   ImageInfo
296     *read_info;
297
298   int
299     c,
300     unique_file;
301
302   MagickBooleanType
303     status;
304
305   size_t
306     length;
307
308   ssize_t
309     offset,
310     strip_offset;
311
312   /*
313     Open image file.
314   */
315   assert(image_info != (const ImageInfo *) NULL);
316   assert(image_info->signature == MagickSignature);
317   if (image_info->debug != MagickFalse)
318     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
319       image_info->filename);
320   assert(exception != (ExceptionInfo *) NULL);
321   assert(exception->signature == MagickSignature);
322   image=AcquireImage(image_info);
323   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
324   if (status == MagickFalse)
325     {
326       image=DestroyImageList(image);
327       return((Image *) NULL);
328     }
329   /*
330     Write raw CCITT Group 4 wrapped as a TIFF image file.
331   */
332   file=(FILE *) NULL;
333   unique_file=AcquireUniqueFileResource(filename);
334   if (unique_file != -1)
335     file=fdopen(unique_file,"wb");
336   if ((unique_file == -1) || (file == (FILE *) NULL))
337     ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
338   length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
339   length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
340   length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
341   length=WriteLSBLong(file,image->columns);
342   length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
343   length=WriteLSBLong(file,image->rows);
344   length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
345   length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
346   length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
347   length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
348   strip_offset=10+(12*14)+4+8;
349   length=WriteLSBLong(file,(size_t) strip_offset);
350   length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
351   length=WriteLSBLong(file,(size_t) image_info->orientation);
352   length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
353   length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
354   length=WriteLSBLong(file,image->rows);
355   length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
356   offset=(ssize_t) ftell(file)-4;
357   length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
358   length=WriteLSBLong(file,(size_t) (strip_offset-8));
359   length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
360   length=WriteLSBLong(file,(size_t) (strip_offset-8));
361   length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
362   length=fwrite("\000\000\000\000",1,4,file);
363   length=WriteLSBLong(file,image->x_resolution);
364   length=WriteLSBLong(file,1);
365   for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
366     (void) fputc(c,file);
367   offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
368   length=WriteLSBLong(file,(unsigned int) length);
369   (void) fclose(file);
370   (void) CloseBlob(image);
371   image=DestroyImage(image);
372   /*
373     Read TIFF image.
374   */
375   read_info=CloneImageInfo((ImageInfo *) NULL);
376   (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
377   image=ReadTIFFImage(read_info,exception);
378   read_info=DestroyImageInfo(read_info);
379   if (image != (Image *) NULL)
380     {
381       (void) CopyMagickString(image->filename,image_info->filename,
382         MaxTextExtent);
383       (void) CopyMagickString(image->magick_filename,image_info->filename,
384         MaxTextExtent);
385       (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
386     }
387   (void) RelinquishUniqueFileResource(filename);
388   return(image);
389 }
390 #endif
391 \f
392 #if defined(MAGICKCORE_TIFF_DELEGATE)
393 /*
394 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
395 %                                                                             %
396 %                                                                             %
397 %                                                                             %
398 %   R e a d T I F F I m a g e                                                 %
399 %                                                                             %
400 %                                                                             %
401 %                                                                             %
402 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
403 %
404 %  ReadTIFFImage() reads a Tagged image file and returns it.  It allocates the
405 %  memory necessary for the new Image structure and returns a pointer to the
406 %  new image.
407 %
408 %  The format of the ReadTIFFImage method is:
409 %
410 %      Image *ReadTIFFImage(const ImageInfo *image_info,
411 %        ExceptionInfo *exception)
412 %
413 %  A description of each parameter follows:
414 %
415 %    o image_info: the image info.
416 %
417 %    o exception: return any errors or warnings in this structure.
418 %
419 */
420
421 static inline size_t MagickMax(const size_t x,const size_t y)
422 {
423   if (x > y)
424     return(x);
425   return(y);
426 }
427
428 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
429 {
430   if (x < y)
431     return(x);
432   return(y);
433 }
434
435 static MagickBooleanType ReadProfile(Image *image,const char *name,
436   unsigned char *datum,ssize_t length)
437 {
438   MagickBooleanType
439     status;
440
441   register ssize_t
442     i;
443
444   StringInfo
445     *profile;
446
447   if (length < 4)
448     return(MagickFalse);
449   i=0;
450   if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"xmp") != 0))
451     {
452       for (i=0; i < (length-4); i+=2)
453         if (LocaleNCompare((char *) (datum+i),"8BIM",4) == 0)
454           break;
455       if (i == length)
456         length-=i;
457       else
458         i=0;
459       if (length < 4)
460         return(MagickFalse);
461     }
462   profile=BlobToStringInfo(datum+i,(size_t) length);
463   if (profile == (StringInfo *) NULL)
464     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
465       image->filename);
466   status=SetImageProfile(image,name,profile);
467   profile=DestroyStringInfo(profile);
468   if (status == MagickFalse)
469     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
470       image->filename);
471   return(MagickTrue);
472 }
473
474 #if defined(__cplusplus) || defined(c_plusplus)
475 extern "C" {
476 #endif
477
478 static int TIFFCloseBlob(thandle_t image)
479 {
480   (void) CloseBlob((Image *) image);
481   return(0);
482 }
483
484 static void TIFFErrors(const char *module,const char *format,va_list error)
485 {
486   char
487     message[MaxTextExtent];
488
489   ExceptionInfo
490     *exception;
491
492 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
493   (void) vsnprintf(message,MaxTextExtent,format,error);
494 #else
495   (void) vsprintf(message,format,error);
496 #endif
497   (void) ConcatenateMagickString(message,".",MaxTextExtent);
498   exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
499   if (exception != (ExceptionInfo *) NULL)
500     (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
501       "`%s'",module);
502 }
503
504 static void TIFFGetProfiles(TIFF *tiff,Image *image)
505 {
506   uint32
507     length;
508
509   unsigned char
510     *profile;
511
512 #if defined(TIFFTAG_ICCPROFILE)
513   length=0;
514   if (TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1)
515     (void) ReadProfile(image,"icc",profile,(ssize_t) length);
516 #endif
517 #if defined(TIFFTAG_PHOTOSHOP)
518   length=0;
519   if (TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1)
520     (void) ReadProfile(image,"8bim",profile,(ssize_t) length);
521 #endif
522 #if defined(TIFFTAG_RICHTIFFIPTC)
523   length=0;
524   if (TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1)
525     {
526       if (TIFFIsByteSwapped(tiff) != 0)
527         TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
528       (void) ReadProfile(image,"iptc",profile,4L*length);
529     }
530 #endif
531 #if defined(TIFFTAG_XMLPACKET)
532   length=0;
533   if (TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1)
534     (void) ReadProfile(image,"xmp",profile,(ssize_t) length);
535 #endif
536   length=0;
537   if (TIFFGetField(tiff,37724,&length,&profile) == 1)
538     (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
539 }
540
541 static void TIFFGetProperties(TIFF *tiff,Image *image)
542 {
543   char
544     *text;
545
546   if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
547     (void) SetImageProperty(image,"tiff:artist",text);
548   if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
549     (void) SetImageProperty(image,"tiff:timestamp",text);
550   if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
551     (void) SetImageProperty(image,"tiff:software",text);
552   if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
553     (void) SetImageProperty(image,"tiff:hostcomputer",text);
554   if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
555     (void) SetImageProperty(image,"tiff:document",text);
556   if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
557     (void) SetImageProperty(image,"tiff:make",text);
558   if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
559     (void) SetImageProperty(image,"tiff:model",text);
560   if (TIFFGetField(tiff,33432,&text) == 1)
561     (void) SetImageProperty(image,"tiff:copyright",text);
562   if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
563     (void) SetImageProperty(image,"label",text);
564   if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
565     (void) SetImageProperty(image,"comment",text);
566 }
567
568 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
569 {
570 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
571   char
572     value[MaxTextExtent];
573
574   register ssize_t
575     i;
576
577   tdir_t
578     directory;
579
580   uint32
581     offset;
582
583   /*
584     Read EXIF properties.
585   */
586   if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) == 0)
587     return;
588   directory=TIFFCurrentDirectory(tiff);
589   if (TIFFReadEXIFDirectory(tiff,offset) == 0)
590     return;
591   for (i=0; exif_info[i].tag != 0; i++)
592   {
593     *value='\0';
594     switch (exif_info[i].type)
595     {
596       case TIFF_ASCII:
597       {
598         char
599           *ascii;
600
601         if (TIFFGetField(tiff,exif_info[i].tag,&ascii) != 0)
602           (void) CopyMagickMemory(value,ascii,MaxTextExtent);
603         break;
604       }
605       case TIFF_SHORT:
606       {
607         uint16
608           shorty;
609
610         if (TIFFGetField(tiff,exif_info[i].tag,&shorty) != 0)
611           (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
612         break;
613       }
614       case TIFF_LONG:
615       {
616         uint32
617           ssize_ty;
618
619         if (TIFFGetField(tiff,exif_info[i].tag,&ssize_ty) != 0)
620           (void) FormatLocaleString(value,MaxTextExtent,"%d",ssize_ty);
621         break;
622       }
623       case TIFF_RATIONAL:
624       case TIFF_SRATIONAL:
625       {
626         float
627           rational;
628
629         if (TIFFGetField(tiff,exif_info[i].tag,&rational) != 0)
630           (void) FormatLocaleString(value,MaxTextExtent,"%g",rational);
631         break;
632       }
633       default:
634         break;
635     }
636     if (*value != '\0')
637       (void) SetImageProperty(image,exif_info[i].property,value);
638   }
639   TIFFSetDirectory(tiff,directory);
640 #else
641   (void) tiff;
642   (void) image;
643 #endif
644 }
645
646 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
647 {
648   *base=(tdata_t *) GetBlobStreamData((Image *) image);
649   if (*base != (tdata_t *) NULL)
650     *size=(toff_t) GetBlobSize((Image *) image);
651   if (*base != (tdata_t *) NULL)
652     return(1);
653   return(0);
654 }
655
656 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
657 {
658   tsize_t
659     count;
660
661   count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
662     (unsigned char *) data);
663   return(count);
664 }
665
666 static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
667   tsample_t sample,ssize_t row,tdata_t scanline)
668 {
669   int32
670     status;
671
672   (void) bits_per_sample;
673   status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
674   return(status);
675 }
676
677 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
678 {
679   return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
680 }
681
682 static toff_t TIFFGetBlobSize(thandle_t image)
683 {
684   return((toff_t) GetBlobSize((Image *) image));
685 }
686
687 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
688 {
689   (void) image;
690   (void) base;
691   (void) size;
692 }
693
694 static void TIFFWarnings(const char *module,const char *format,va_list warning)
695 {
696   char
697     message[MaxTextExtent];
698
699   ExceptionInfo
700     *exception;
701
702 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
703   (void) vsnprintf(message,MaxTextExtent,format,warning);
704 #else
705   (void) vsprintf(message,format,warning);
706 #endif
707   (void) ConcatenateMagickString(message,".",MaxTextExtent);
708   exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
709   if (exception != (ExceptionInfo *) NULL)
710     (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
711       message,"`%s'",module);
712 }
713
714 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
715 {
716   tsize_t
717     count;
718
719   count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
720     (unsigned char *) data);
721   return(count);
722 }
723
724 #if defined(__cplusplus) || defined(c_plusplus)
725 }
726 #endif
727
728 static Image *ReadTIFFImage(const ImageInfo *image_info,
729   ExceptionInfo *exception)
730 {
731   typedef enum
732   {
733     ReadSingleSampleMethod,
734     ReadRGBAMethod,
735     ReadCMYKAMethod,
736     ReadStripMethod,
737     ReadTileMethod,
738     ReadGenericMethod
739   } TIFFMethodType;
740
741   const char
742     *option;
743
744   float
745     *chromaticity,
746     x_position,
747     y_position,
748     x_resolution,
749     y_resolution;
750
751   Image
752     *image;
753
754   MagickBooleanType
755     associated_alpha,
756     debug,
757     status;
758
759   MagickSizeType
760     number_pixels;
761
762   QuantumInfo
763     *quantum_info;
764
765   QuantumType
766     quantum_type;
767
768   register ssize_t
769     i;
770
771   size_t
772     length,
773     lsb_first,
774     pad;
775
776   ssize_t
777     y;
778
779   TIFF
780     *tiff;
781
782   TIFFErrorHandler
783     error_handler,
784     warning_handler;
785
786   TIFFMethodType
787     method;
788
789   uint16
790     compress_tag,
791     bits_per_sample,
792     endian,
793     extra_samples,
794     interlace,
795     max_sample_value,
796     min_sample_value,
797     orientation,
798     pages,
799     photometric,
800     *sample_info,
801     sample_format,
802     samples_per_pixel,
803     units,
804     value;
805
806   uint32
807     height,
808     rows_per_strip,
809     width;
810
811   unsigned char
812     *pixels;
813
814   /*
815     Open image.
816   */
817   assert(image_info != (const ImageInfo *) NULL);
818   assert(image_info->signature == MagickSignature);
819   if (image_info->debug != MagickFalse)
820     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
821       image_info->filename);
822   assert(exception != (ExceptionInfo *) NULL);
823   assert(exception->signature == MagickSignature);
824   image=AcquireImage(image_info);
825   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
826   if (status == MagickFalse)
827     {
828       image=DestroyImageList(image);
829       return((Image *) NULL);
830     }
831   (void) MagickSetThreadValue(tiff_exception,exception);
832   error_handler=TIFFSetErrorHandler(TIFFErrors);
833   warning_handler=TIFFSetWarningHandler(TIFFWarnings);
834   tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
835     TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
836     TIFFUnmapBlob);
837   if (tiff == (TIFF *) NULL)
838     {
839       (void) TIFFSetWarningHandler(warning_handler);
840       (void) TIFFSetErrorHandler(error_handler);
841       image=DestroyImageList(image);
842       return((Image *) NULL);
843     }
844   debug=IsEventLogging();
845   (void) debug;
846   if (image_info->number_scenes != 0)
847     {
848       /*
849         Generate blank images for subimage specification (e.g. image.tif[4].
850       */
851       for (i=0; i < (ssize_t) image_info->scene; i++)
852       {
853         (void) TIFFReadDirectory(tiff);
854         AcquireNextImage(image_info,image);
855         if (GetNextImageInList(image) == (Image *) NULL)
856           {
857             image=DestroyImageList(image);
858             return((Image *) NULL);
859           }
860         image=SyncNextImageInList(image);
861       }
862     }
863   do
864   {
865     if (0 && (image_info->verbose != MagickFalse))
866       TIFFPrintDirectory(tiff,stdout,MagickFalse);
867     (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
868       "lsb" : "msb");
869     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
870     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
871     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
872     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGELENGTH,&height);
873     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
874     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace);
875     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample);
876     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format);
877     if (sample_format == SAMPLEFORMAT_IEEEFP)
878       (void) SetImageProperty(image,"quantum:format","floating-point");
879     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value);
880     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value);
881     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric);
882     switch (photometric)
883     {
884       case PHOTOMETRIC_MINISBLACK:
885       {
886         (void) SetImageProperty(image,"tiff:photometric","min-is-black");
887         break;
888       }
889       case PHOTOMETRIC_MINISWHITE:
890       {
891         (void) SetImageProperty(image,"tiff:photometric","min-is-white");
892         break;
893       }
894       case PHOTOMETRIC_PALETTE:
895       {
896         (void) SetImageProperty(image,"tiff:photometric","palette");
897         break;
898       }
899       case PHOTOMETRIC_RGB:
900       {
901         (void) SetImageProperty(image,"tiff:photometric","RGB");
902         break;
903       }
904       case PHOTOMETRIC_CIELAB:
905       {
906         (void) SetImageProperty(image,"tiff:photometric","CIELAB");
907         break;
908       }
909       case PHOTOMETRIC_SEPARATED:
910       {
911         (void) SetImageProperty(image,"tiff:photometric","separated");
912         break;
913       }
914       case PHOTOMETRIC_YCBCR:
915       {
916         (void) SetImageProperty(image,"tiff:photometric","YCBCR");
917         break;
918       }
919       default:
920       {
921         (void) SetImageProperty(image,"tiff:photometric","unknown");
922         break;
923       }
924     }
925     if (image->debug != MagickFalse)
926       {
927         (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
928           (unsigned int) width,(unsigned int) height);
929         (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
930           interlace);
931         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
932           "Bits per sample: %u",bits_per_sample);
933         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
934           "Min sample value: %u",min_sample_value);
935         (void) LogMagickEvent(CoderEvent,GetMagickModule(),
936           "Max sample value: %u",max_sample_value);
937         (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
938           "interpretation: %s",GetImageProperty(image,"tiff:photometric"));
939       }
940     image->columns=(size_t) width;
941     image->rows=(size_t) height;
942     image->depth=(size_t) bits_per_sample;
943     if (image->debug != MagickFalse)
944       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
945         (double) image->depth);
946     lsb_first=1;
947     image->endian=MSBEndian;
948     if ((int) (*(char *) &lsb_first) != 0)
949       image->endian=LSBEndian;
950     if (photometric == PHOTOMETRIC_SEPARATED)
951       image->colorspace=CMYKColorspace;
952     if (photometric == PHOTOMETRIC_CIELAB)
953       image->colorspace=LabColorspace;
954     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
955       &samples_per_pixel);
956     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
957     x_resolution=(float) image->x_resolution;
958     y_resolution=(float) image->y_resolution;
959     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution);
960     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
961     image->x_resolution=x_resolution;
962     image->y_resolution=y_resolution;
963     x_position=(float) image->page.x/x_resolution;
964     y_position=(float) image->page.y/y_resolution;
965     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
966     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
967     image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
968     image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
969     image->orientation=(OrientationType) orientation;
970     chromaticity=(float *) NULL;
971     (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
972     if (chromaticity != (float *) NULL)
973       {
974         image->chromaticity.white_point.x=chromaticity[0];
975         image->chromaticity.white_point.y=chromaticity[1];
976       }
977     chromaticity=(float *) NULL;
978     (void) TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity);
979     if (chromaticity != (float *) NULL)
980       {
981         image->chromaticity.red_primary.x=chromaticity[0];
982         image->chromaticity.red_primary.y=chromaticity[1];
983         image->chromaticity.green_primary.x=chromaticity[2];
984         image->chromaticity.green_primary.y=chromaticity[3];
985         image->chromaticity.blue_primary.x=chromaticity[4];
986         image->chromaticity.blue_primary.y=chromaticity[5];
987       }
988     TIFFGetProperties(tiff,image);
989     option=GetImageOption(image_info,"tiff:exif");
990     if ((option != (const char *) NULL) &&
991         (IsMagickTrue(option) != MagickFalse))
992       TIFFGetEXIFProperties(tiff,image);
993     TIFFGetProfiles(tiff,image);
994     /*
995       Allocate memory for the image and pixel buffer.
996     */
997 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
998     if ((compress_tag != COMPRESSION_NONE) &&
999         (TIFFIsCODECConfigured(compress_tag) == 0))
1000       {
1001         TIFFClose(tiff);
1002         ThrowReaderException(CoderError,"CompressNotSupported");
1003       }
1004 #endif
1005     switch (compress_tag)
1006     {
1007       case COMPRESSION_NONE: image->compression=NoCompression; break;
1008       case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1009       case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1010       case COMPRESSION_JPEG:
1011       {
1012          image->compression=JPEGCompression;
1013 #if defined(JPEG_SUPPORT)
1014          {
1015            char
1016              sampling_factor[MaxTextExtent];
1017
1018            uint16
1019              horizontal,
1020              vertical;
1021
1022            (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
1023              &horizontal,&vertical);
1024            (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
1025              horizontal,vertical);
1026            (void) SetImageProperty(image,"jpeg:sampling-factor",
1027              sampling_factor);
1028            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1029              "Sampling Factors: %s",sampling_factor);
1030            if ((samples_per_pixel > 1) && (photometric == PHOTOMETRIC_YCBCR))
1031              {
1032                (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,
1033                  JPEGCOLORMODE_RGB);
1034                photometric=PHOTOMETRIC_RGB;
1035              }
1036          }
1037 #endif
1038         break;
1039       }
1040       case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1041 #if defined(COMPRESSION_LZMA)
1042       case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1043 #endif
1044       case COMPRESSION_LZW: image->compression=LZWCompression; break;
1045       case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1046       case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1047       default: image->compression=RLECompression; break;
1048     }
1049     quantum_info=AcquireQuantumInfo(image_info,image);
1050     if (quantum_info == (QuantumInfo *) NULL)
1051       {
1052         TIFFClose(tiff);
1053         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1054       }
1055     if (sample_format == SAMPLEFORMAT_UINT)
1056       status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1057     if (sample_format == SAMPLEFORMAT_INT)
1058       status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1059     if (sample_format == SAMPLEFORMAT_IEEEFP)
1060       status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1061     if (status == MagickFalse)
1062       {
1063         TIFFClose(tiff);
1064         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1065       }
1066     status=MagickTrue;
1067     switch (photometric)
1068     {
1069       case PHOTOMETRIC_MINISBLACK:
1070       {
1071         quantum_info->min_is_white=MagickFalse;
1072         break;
1073       }
1074       case PHOTOMETRIC_MINISWHITE:
1075       {
1076         quantum_info->min_is_white=MagickTrue;
1077         break;
1078       }
1079       default:
1080         break;
1081     }
1082     associated_alpha=MagickFalse;
1083     extra_samples=0;
1084     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1085       &sample_info);
1086     if (extra_samples == 0)
1087       {
1088         if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1089           image->matte=MagickTrue;
1090       }
1091     else
1092       for (i=0; i < extra_samples; i++)
1093       {
1094         image->matte=MagickTrue;
1095         if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1096           SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1097       }
1098     option=GetImageOption(image_info,"tiff:alpha");
1099     if (option != (const char *) NULL)
1100       associated_alpha=LocaleCompare(option,"associated") == 0 ? MagickTrue :
1101         MagickFalse;
1102     if (image->matte != MagickFalse)
1103       (void) SetImageProperty(image,"tiff:alpha",
1104         associated_alpha != MagickFalse ? "associated" : "unassociated");
1105     if ((photometric == PHOTOMETRIC_PALETTE) &&
1106         (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1107       {
1108         size_t
1109           colors;
1110
1111         colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1112         if (AcquireImageColormap(image,colors) == MagickFalse)
1113           {
1114             TIFFClose(tiff);
1115             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1116           }
1117       }
1118     if (units == RESUNIT_INCH)
1119       image->units=PixelsPerInchResolution;
1120     if (units == RESUNIT_CENTIMETER)
1121       image->units=PixelsPerCentimeterResolution;
1122     value=(unsigned short) image->scene;
1123     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages);
1124     image->scene=value;
1125     if (image_info->ping != MagickFalse)
1126       {
1127         if (image_info->number_scenes != 0)
1128           if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1129             break;
1130         goto next_tiff_frame;
1131       }
1132     method=ReadGenericMethod;
1133     if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) != 0)
1134       {
1135         char
1136           value[MaxTextExtent];
1137
1138         method=ReadStripMethod;
1139         (void) FormatLocaleString(value,MaxTextExtent,"%u",
1140           (unsigned int) rows_per_strip);
1141         (void) SetImageProperty(image,"tiff:rows-per-strip",value);
1142       }
1143     if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
1144       method=ReadRGBAMethod;
1145     if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
1146       method=ReadCMYKAMethod;
1147     if ((photometric != PHOTOMETRIC_RGB) &&
1148         (photometric != PHOTOMETRIC_CIELAB) &&
1149         (photometric != PHOTOMETRIC_SEPARATED))
1150       method=ReadGenericMethod;
1151     if (image->storage_class == PseudoClass)
1152       method=ReadSingleSampleMethod;
1153     if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1154         (photometric == PHOTOMETRIC_MINISWHITE))
1155       method=ReadSingleSampleMethod;
1156     if ((photometric != PHOTOMETRIC_SEPARATED) &&
1157         (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1158       method=ReadGenericMethod;
1159     if (image->compression == JPEGCompression)
1160       method=ReadGenericMethod;
1161     if (TIFFIsTiled(tiff) != MagickFalse)
1162       method=ReadTileMethod;
1163     quantum_type=RGBQuantum;
1164     pixels=GetQuantumPixels(quantum_info);
1165     switch (method)
1166     {
1167       case ReadSingleSampleMethod:
1168       {
1169         /*
1170           Convert TIFF image to PseudoClass MIFF image.
1171         */
1172         if ((image->storage_class == PseudoClass) &&
1173             (photometric == PHOTOMETRIC_PALETTE))
1174           {
1175             size_t
1176               range;
1177
1178             uint16
1179               *blue_colormap,
1180               *green_colormap,
1181               *red_colormap;
1182
1183             /*
1184               Initialize colormap.
1185             */
1186             (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1187               &green_colormap,&blue_colormap);
1188             range=255;  /* might be old style 8-bit colormap */
1189             for (i=0; i < (ssize_t) image->colors; i++)
1190               if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1191                   (blue_colormap[i] >= 256))
1192                 {
1193                   range=65535;
1194                   break;
1195                 }
1196             for (i=0; i < (ssize_t) image->colors; i++)
1197             {
1198               image->colormap[i].red=ClampToQuantum(((double) QuantumRange*
1199                 red_colormap[i])/range);
1200               image->colormap[i].green=ClampToQuantum(((double) QuantumRange*
1201                 green_colormap[i])/range);
1202               image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*
1203                 blue_colormap[i])/range);
1204             }
1205           }
1206         quantum_type=IndexQuantum;
1207         pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1208         if (image->matte != MagickFalse)
1209           {
1210             if (image->storage_class != PseudoClass)
1211               {
1212                 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1213                   GrayAlphaQuantum;
1214                 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1215               }
1216             else
1217               {
1218                 quantum_type=IndexAlphaQuantum;
1219                 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1220               }
1221           }
1222         else
1223           if (image->storage_class != PseudoClass)
1224             {
1225               quantum_type=GrayQuantum;
1226               pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1227             }
1228         status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1229         if (status == MagickFalse)
1230           {
1231             TIFFClose(tiff);
1232             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1233           }
1234         pixels=GetQuantumPixels(quantum_info);
1235         for (y=0; y < (ssize_t) image->rows; y++)
1236         {
1237           int
1238             status;
1239
1240           register Quantum
1241             *restrict q;
1242
1243           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1244           if (status == -1)
1245             break;
1246           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1247           if (q == (Quantum *) NULL)
1248             break;
1249           length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1250             quantum_type,pixels,exception);
1251           (void) length;
1252           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1253             break;
1254           if (image->previous == (Image *) NULL)
1255             {
1256               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1257                 image->rows);
1258               if (status == MagickFalse)
1259                 break;
1260             }
1261         }
1262         break;
1263       }
1264       case ReadRGBAMethod:
1265       {
1266         /*
1267           Convert TIFF image to DirectClass MIFF image.
1268         */
1269         pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1270         quantum_type=RGBQuantum;
1271         if (image->matte != MagickFalse)
1272           {
1273             quantum_type=RGBAQuantum;
1274             pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1275           }
1276         if (image->colorspace == CMYKColorspace)
1277           {
1278             pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1279             quantum_type=CMYKQuantum;
1280             if (image->matte != MagickFalse)
1281               {
1282                 quantum_type=CMYKAQuantum;
1283                 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1284               }
1285           }
1286         status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1287         if (status == MagickFalse)
1288           {
1289             TIFFClose(tiff);
1290             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1291           }
1292         pixels=GetQuantumPixels(quantum_info);
1293         for (y=0; y < (ssize_t) image->rows; y++)
1294         {
1295           int
1296             status;
1297
1298           register Quantum
1299             *restrict q;
1300
1301           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1302           if (status == -1)
1303             break;
1304           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1305           if (q == (Quantum *) NULL)
1306             break;
1307           length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1308             quantum_type,pixels,exception);
1309           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1310             break;
1311           if (image->previous == (Image *) NULL)
1312             {
1313               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1314                 image->rows);
1315               if (status == MagickFalse)
1316                 break;
1317             }
1318         }
1319         break;
1320       }
1321       case ReadCMYKAMethod:
1322       {
1323         /*
1324           Convert TIFF image to DirectClass MIFF image.
1325         */
1326         for (i=0; i < (ssize_t) samples_per_pixel; i++)
1327         {
1328           for (y=0; y < (ssize_t) image->rows; y++)
1329           {
1330             register Quantum
1331               *restrict q;
1332
1333             int
1334               status;
1335
1336             status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1337               pixels);
1338             if (status == -1)
1339               break;
1340             q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1341             if (q == (Quantum *) NULL)
1342               break;
1343             if (image->colorspace != CMYKColorspace)
1344               switch (i)
1345               {
1346                 case 0: quantum_type=RedQuantum; break;
1347                 case 1: quantum_type=GreenQuantum; break;
1348                 case 2: quantum_type=BlueQuantum; break;
1349                 case 3: quantum_type=AlphaQuantum; break;
1350                 default: quantum_type=UndefinedQuantum; break;
1351               }
1352             else
1353               switch (i)
1354               {
1355                 case 0: quantum_type=CyanQuantum; break;
1356                 case 1: quantum_type=MagentaQuantum; break;
1357                 case 2: quantum_type=YellowQuantum; break;
1358                 case 3: quantum_type=BlackQuantum; break;
1359                 case 4: quantum_type=AlphaQuantum; break;
1360                 default: quantum_type=UndefinedQuantum; break;
1361               }
1362             length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1363               quantum_type,pixels,exception);
1364             if (SyncAuthenticPixels(image,exception) == MagickFalse)
1365               break;
1366           }
1367           if (image->previous == (Image *) NULL)
1368             {
1369               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1370                 image->rows);
1371               if (status == MagickFalse)
1372                 break;
1373             }
1374         }
1375         break;
1376       }
1377       case ReadStripMethod:
1378       {
1379         register unsigned char
1380           *p;
1381
1382         /*
1383           Convert stripped TIFF image to DirectClass MIFF image.
1384         */
1385         i=0;
1386         p=(unsigned char *) NULL;
1387         for (y=0; y < (ssize_t) image->rows; y++)
1388         {
1389           register ssize_t
1390             x;
1391
1392           register Quantum
1393             *restrict q;
1394
1395           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1396           if (q == (Quantum *) NULL)
1397             break;
1398           if (i == 0)
1399             {
1400               if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1401                 break;
1402               i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1403                 image->rows-y);
1404             }
1405           i--;
1406           p=(unsigned char *) (((uint32 *) pixels)+image->columns*i);
1407           for (x=0; x < (ssize_t) image->columns; x++)
1408           {
1409             SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1410               (TIFFGetR(*p))),q);
1411             SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1412               (TIFFGetG(*p))),q);
1413             SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1414               (TIFFGetB(*p))),q);
1415             if (image->matte != MagickFalse)
1416               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1417                 (TIFFGetA(*p))),q);
1418             p++;
1419             q+=GetPixelChannels(image);
1420           }
1421           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1422             break;
1423           if (image->previous == (Image *) NULL)
1424             {
1425               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1426                 image->rows);
1427               if (status == MagickFalse)
1428                 break;
1429             }
1430         }
1431         break;
1432       }
1433       case ReadTileMethod:
1434       {
1435         register uint32
1436           *p;
1437
1438         uint32
1439           *tile_pixels,
1440           columns,
1441           rows;
1442
1443         size_t
1444           number_pixels;
1445
1446         /*
1447           Convert tiled TIFF image to DirectClass MIFF image.
1448         */
1449         if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) == 0) ||
1450             (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) == 0))
1451           {
1452             TIFFClose(tiff);
1453             ThrowReaderException(CoderError,"ImageIsNotTiled");
1454           }
1455         (void) SetImageStorageClass(image,DirectClass,&image->exception);
1456         number_pixels=columns*rows;
1457         tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
1458           sizeof(*tile_pixels));
1459         if (tile_pixels == (uint32 *) NULL)
1460           {
1461             TIFFClose(tiff);
1462             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1463           }
1464         for (y=0; y < (ssize_t) image->rows; y+=rows)
1465         {
1466           register ssize_t
1467             x;
1468
1469           register Quantum
1470             *restrict q,
1471             *restrict tile;
1472
1473           size_t
1474             columns_remaining,
1475             rows_remaining;
1476
1477           rows_remaining=image->rows-y;
1478           if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1479             rows_remaining=rows;
1480           tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1481             exception);
1482           if (tile == (Quantum *) NULL)
1483             break;
1484           for (x=0; x < (ssize_t) image->columns; x+=columns)
1485           {
1486             size_t
1487               column,
1488               row;
1489
1490             if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1491               break;
1492             columns_remaining=image->columns-x;
1493             if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1494               columns_remaining=columns;
1495             p=tile_pixels+(rows-rows_remaining)*columns;
1496             q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1497               x);
1498             for (row=rows_remaining; row > 0; row--)
1499             {
1500               if (image->matte != MagickFalse)
1501                 for (column=columns_remaining; column > 0; column--)
1502                 {
1503                   SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1504                     TIFFGetR(*p)),q);
1505                   SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1506                     TIFFGetG(*p)),q);
1507                   SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1508                     TIFFGetB(*p)),q);
1509                   SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1510                     TIFFGetA(*p)),q);
1511                   p++;
1512                   q+=GetPixelChannels(image);
1513                 }
1514               else
1515                 for (column=columns_remaining; column > 0; column--)
1516                 {
1517                   SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1518                     TIFFGetR(*p)),q);
1519                   SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1520                     TIFFGetG(*p)),q);
1521                   SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1522                     TIFFGetB(*p)),q);
1523                   p++;
1524                   q+=GetPixelChannels(image);
1525                 }
1526               p+=columns-columns_remaining;
1527               q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1528             }
1529           }
1530           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1531             break;
1532           if (image->previous == (Image *) NULL)
1533             {
1534               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1535                 image->rows);
1536               if (status == MagickFalse)
1537                 break;
1538             }
1539         }
1540         tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
1541         break;
1542       }
1543       case ReadGenericMethod:
1544       default:
1545       {
1546         register uint32
1547           *p;
1548
1549         uint32
1550           *pixels;
1551
1552         /*
1553           Convert TIFF image to DirectClass MIFF image.
1554         */
1555         number_pixels=(MagickSizeType) image->columns*image->rows;
1556         if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
1557             (number_pixels*sizeof(uint32))))
1558           {
1559             TIFFClose(tiff);
1560             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1561           }
1562         pixels=(uint32 *) AcquireQuantumMemory(image->columns,image->rows*
1563           sizeof(uint32));
1564         if (pixels == (uint32 *) NULL)
1565           {
1566             TIFFClose(tiff);
1567             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1568           }
1569         (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
1570           (uint32) image->rows,(uint32 *) pixels,0);
1571         /*
1572           Convert image to DirectClass pixel packets.
1573         */
1574         p=pixels+number_pixels-1;
1575         for (y=0; y < (ssize_t) image->rows; y++)
1576         {
1577           register ssize_t
1578             x;
1579
1580           register Quantum
1581             *restrict q;
1582
1583           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1584           if (q == (Quantum *) NULL)
1585             break;
1586           q+=GetPixelChannels(image)*(image->columns-1);
1587           for (x=0; x < (ssize_t) image->columns; x++)
1588           {
1589             SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1590               TIFFGetR(*p)),q);
1591             SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1592               TIFFGetG(*p)),q);
1593             SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1594               TIFFGetB(*p)),q);
1595             if (image->matte != MagickFalse)
1596               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1597                 TIFFGetA(*p)),q);
1598             p--;
1599             q-=GetPixelChannels(image);;
1600           }
1601           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1602             break;
1603           if (image->previous == (Image *) NULL)
1604             {
1605               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1606                 image->rows);
1607               if (status == MagickFalse)
1608                 break;
1609             }
1610         }
1611         pixels=(uint32 *) RelinquishMagickMemory(pixels);
1612         break;
1613       }
1614     }
1615     SetQuantumImageType(image,quantum_type);
1616   next_tiff_frame:
1617     if ((photometric == PHOTOMETRIC_LOGL) ||
1618         (photometric == PHOTOMETRIC_MINISBLACK) ||
1619         (photometric == PHOTOMETRIC_MINISWHITE))
1620       {
1621         image->type=GrayscaleType;
1622         if (bits_per_sample == 1)
1623           image->type=BilevelType;
1624       }
1625     if (image->storage_class == PseudoClass)
1626       image->depth=GetImageDepth(image,exception);
1627     image->endian=MSBEndian;
1628     if (endian == FILLORDER_LSB2MSB)
1629       image->endian=LSBEndian;
1630     if ((photometric == PHOTOMETRIC_LOGL) ||
1631         (photometric == PHOTOMETRIC_MINISBLACK) ||
1632         (photometric == PHOTOMETRIC_MINISWHITE))
1633       {
1634          image->type=GrayscaleType;
1635          if (bits_per_sample == 1)
1636            image->type=BilevelType;
1637       }
1638     /*
1639       Proceed to next image.
1640     */
1641     if (image_info->number_scenes != 0)
1642       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1643         break;
1644     status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1645     if (status == MagickTrue)
1646       {
1647         /*
1648           Allocate next image structure.
1649         */
1650         AcquireNextImage(image_info,image);
1651         if (GetNextImageInList(image) == (Image *) NULL)
1652           {
1653             image=DestroyImageList(image);
1654             return((Image *) NULL);
1655           }
1656         image=SyncNextImageInList(image);
1657         status=SetImageProgress(image,LoadImagesTag,image->scene-1,
1658           image->scene);
1659         if (status == MagickFalse)
1660           break;
1661       }
1662     quantum_info=DestroyQuantumInfo(quantum_info);
1663   } while (status == MagickTrue);
1664   (void) TIFFSetWarningHandler(warning_handler);
1665   (void) TIFFSetErrorHandler(error_handler);
1666   TIFFClose(tiff);
1667   return(GetFirstImageInList(image));
1668 }
1669 #endif
1670 \f
1671 /*
1672 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1673 %                                                                             %
1674 %                                                                             %
1675 %                                                                             %
1676 %   R e g i s t e r T I F F I m a g e                                         %
1677 %                                                                             %
1678 %                                                                             %
1679 %                                                                             %
1680 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1681 %
1682 %  RegisterTIFFImage() adds properties for the TIFF image format to
1683 %  the list of supported formats.  The properties include the image format
1684 %  tag, a method to read and/or write the format, whether the format
1685 %  supports the saving of more than one frame to the same file or blob,
1686 %  whether the format supports native in-memory I/O, and a brief
1687 %  description of the format.
1688 %
1689 %  The format of the RegisterTIFFImage method is:
1690 %
1691 %      size_t RegisterTIFFImage(void)
1692 %
1693 */
1694 ModuleExport size_t RegisterTIFFImage(void)
1695 {
1696 #define TIFFDescription  "Tagged Image File Format"
1697
1698   char
1699     version[MaxTextExtent];
1700
1701   MagickInfo
1702     *entry;
1703
1704   if (tiff_semaphore == (SemaphoreInfo *) NULL)
1705     tiff_semaphore=AllocateSemaphoreInfo();
1706   LockSemaphoreInfo(tiff_semaphore);
1707   if (instantiate_key == MagickFalse)
1708     {
1709       if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
1710         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1711       instantiate_key=MagickTrue;
1712     }
1713   UnlockSemaphoreInfo(tiff_semaphore);
1714   *version='\0';
1715 #if defined(TIFF_VERSION)
1716   (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
1717 #endif
1718 #if defined(MAGICKCORE_TIFF_DELEGATE)
1719   {
1720     const char
1721       *p;
1722
1723     register ssize_t
1724       i;
1725
1726     p=TIFFGetVersion();
1727     for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
1728       version[i]=(*p++);
1729     version[i]='\0';
1730   }
1731 #endif
1732
1733   entry=SetMagickInfo("GROUP4");
1734 #if defined(MAGICKCORE_TIFF_DELEGATE)
1735   entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
1736   entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
1737 #endif
1738   entry->raw=MagickTrue;
1739   entry->endian_support=MagickTrue;
1740   entry->adjoin=MagickFalse;
1741   entry->format_type=ImplicitFormatType;
1742   entry->seekable_stream=MagickTrue;
1743   entry->thread_support=NoThreadSupport;
1744   entry->description=ConstantString("Raw CCITT Group4");
1745   entry->module=ConstantString("TIFF");
1746   (void) RegisterMagickInfo(entry);
1747   entry=SetMagickInfo("PTIF");
1748 #if defined(MAGICKCORE_TIFF_DELEGATE)
1749   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1750   entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1751 #endif
1752   entry->endian_support=MagickTrue;
1753   entry->seekable_stream=MagickTrue;
1754   entry->thread_support=NoThreadSupport;
1755   entry->description=ConstantString("Pyramid encoded TIFF");
1756   entry->module=ConstantString("TIFF");
1757   (void) RegisterMagickInfo(entry);
1758   entry=SetMagickInfo("TIF");
1759 #if defined(MAGICKCORE_TIFF_DELEGATE)
1760   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1761   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1762 #endif
1763   entry->endian_support=MagickTrue;
1764   entry->seekable_stream=MagickTrue;
1765   entry->stealth=MagickTrue;
1766   entry->thread_support=NoThreadSupport;
1767   entry->description=ConstantString(TIFFDescription);
1768   if (*version != '\0')
1769     entry->version=ConstantString(version);
1770   entry->module=ConstantString("TIFF");
1771   (void) RegisterMagickInfo(entry);
1772   entry=SetMagickInfo("TIFF");
1773 #if defined(MAGICKCORE_TIFF_DELEGATE)
1774   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1775   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1776 #endif
1777   entry->magick=(IsImageFormatHandler *) IsTIFF;
1778   entry->endian_support=MagickTrue;
1779   entry->seekable_stream=MagickTrue;
1780   entry->thread_support=NoThreadSupport;
1781   entry->description=ConstantString(TIFFDescription);
1782   if (*version != '\0')
1783     entry->version=ConstantString(version);
1784   entry->module=ConstantString("TIFF");
1785   (void) RegisterMagickInfo(entry);
1786   entry=SetMagickInfo("TIFF64");
1787 #if defined(TIFF_VERSION_BIG)
1788   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1789   entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1790 #endif
1791   entry->adjoin=MagickFalse;
1792   entry->endian_support=MagickTrue;
1793   entry->seekable_stream=MagickTrue;
1794   entry->thread_support=NoThreadSupport;
1795   entry->description=ConstantString("Tagged Image File Format (64-bit)");
1796   if (*version != '\0')
1797     entry->version=ConstantString(version);
1798   entry->module=ConstantString("TIFF");
1799   (void) RegisterMagickInfo(entry);
1800   return(MagickImageCoderSignature);
1801 }
1802 \f
1803 /*
1804 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1805 %                                                                             %
1806 %                                                                             %
1807 %                                                                             %
1808 %   U n r e g i s t e r T I F F I m a g e                                     %
1809 %                                                                             %
1810 %                                                                             %
1811 %                                                                             %
1812 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1813 %
1814 %  UnregisterTIFFImage() removes format registrations made by the TIFF module
1815 %  from the list of supported formats.
1816 %
1817 %  The format of the UnregisterTIFFImage method is:
1818 %
1819 %      UnregisterTIFFImage(void)
1820 %
1821 */
1822 ModuleExport void UnregisterTIFFImage(void)
1823 {
1824   (void) UnregisterMagickInfo("RAWGROUP4");
1825   (void) UnregisterMagickInfo("PTIF");
1826   (void) UnregisterMagickInfo("TIF");
1827   (void) UnregisterMagickInfo("TIFF");
1828   (void) UnregisterMagickInfo("TIFF64");
1829   if (tiff_semaphore == (SemaphoreInfo *) NULL)
1830     tiff_semaphore=AllocateSemaphoreInfo();
1831   LockSemaphoreInfo(tiff_semaphore);
1832   if (instantiate_key != MagickFalse)
1833     if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
1834       ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1835   instantiate_key=MagickFalse;
1836   UnlockSemaphoreInfo(tiff_semaphore);
1837   DestroySemaphoreInfo(&tiff_semaphore);
1838 }
1839 \f
1840 #if defined(MAGICKCORE_TIFF_DELEGATE)
1841 /*
1842 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1843 %                                                                             %
1844 %                                                                             %
1845 %                                                                             %
1846 %   W r i t e G R O U P 4 I m a g e                                           %
1847 %                                                                             %
1848 %                                                                             %
1849 %                                                                             %
1850 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1851 %
1852 %  WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
1853 %
1854 %  The format of the WriteGROUP4Image method is:
1855 %
1856 %      MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
1857 %        Image *image,ExceptionInfo *)
1858 %
1859 %  A description of each parameter follows:
1860 %
1861 %    o image_info: the image info.
1862 %
1863 %    o image:  The image.
1864 %
1865 %    o exception: return any errors or warnings in this structure.
1866 %
1867 */
1868 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
1869   Image *image,ExceptionInfo *exception)
1870 {
1871   char
1872     filename[MaxTextExtent];
1873
1874   FILE
1875     *file;
1876
1877   Image
1878     *huffman_image;
1879
1880   ImageInfo
1881     *write_info;
1882
1883   int
1884     unique_file;
1885
1886   MagickBooleanType
1887     status;
1888
1889   register ssize_t
1890     i;
1891
1892   ssize_t
1893     count;
1894
1895   TIFF
1896     *tiff;
1897
1898   toff_t
1899     *byte_count,
1900     strip_size;
1901
1902   unsigned char
1903     *buffer;
1904
1905   /*
1906     Write image as CCITT Group4 TIFF image to a temporary file.
1907   */
1908   assert(image_info != (const ImageInfo *) NULL);
1909   assert(image_info->signature == MagickSignature);
1910   assert(image != (Image *) NULL);
1911   assert(image->signature == MagickSignature);
1912   if (image->debug != MagickFalse)
1913     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1914   assert(exception != (ExceptionInfo *) NULL);
1915   assert(exception->signature == MagickSignature);
1916   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1917   if (status == MagickFalse)
1918     return(status);
1919   huffman_image=CloneImage(image,0,0,MagickTrue,exception);
1920   if (huffman_image == (Image *) NULL)
1921     {
1922       (void) CloseBlob(image);
1923       return(MagickFalse);
1924     }
1925   huffman_image->endian=MSBEndian;
1926   file=(FILE *) NULL;
1927   unique_file=AcquireUniqueFileResource(filename);
1928   if (unique_file != -1)
1929     file=fdopen(unique_file,"wb");
1930   if ((unique_file == -1) || (file == (FILE *) NULL))
1931     {
1932       ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
1933         filename);
1934       return(MagickFalse);
1935     }
1936   (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
1937     filename);
1938   (void) SetImageType(huffman_image,BilevelType);
1939   write_info=CloneImageInfo((ImageInfo *) NULL);
1940   SetImageInfoFile(write_info,file);
1941   write_info->compression=Group4Compression;
1942   write_info->type=BilevelType;
1943   (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
1944   status=WriteTIFFImage(write_info,huffman_image,exception);
1945   (void) fflush(file);
1946   write_info=DestroyImageInfo(write_info);
1947   if (status == MagickFalse)
1948     {
1949       huffman_image=DestroyImage(huffman_image);
1950       (void) fclose(file);
1951       (void) RelinquishUniqueFileResource(filename);
1952       return(MagickFalse);
1953     }
1954   tiff=TIFFOpen(filename,"rb");
1955   if (tiff == (TIFF *) NULL)
1956     {
1957       huffman_image=DestroyImage(huffman_image);
1958       (void) fclose(file);
1959       (void) RelinquishUniqueFileResource(filename);
1960       ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
1961         image_info->filename);
1962       return(MagickFalse);
1963     }
1964   /*
1965     Allocate raw strip buffer.
1966   */
1967   if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
1968     {
1969       TIFFClose(tiff);
1970       huffman_image=DestroyImage(huffman_image);
1971       (void) fclose(file);
1972       (void) RelinquishUniqueFileResource(filename);
1973       return(MagickFalse);
1974     }
1975   strip_size=byte_count[0];
1976   for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
1977     if (byte_count[i] > strip_size)
1978       strip_size=byte_count[i];
1979   buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
1980     sizeof(*buffer));
1981   if (buffer == (unsigned char *) NULL)
1982     {
1983       TIFFClose(tiff);
1984       huffman_image=DestroyImage(huffman_image);
1985       (void) fclose(file);
1986       (void) RelinquishUniqueFileResource(filename);
1987       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1988         image_info->filename);
1989     }
1990   /*
1991     Compress runlength encoded to 2D Huffman pixels.
1992   */
1993   for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
1994   {
1995     count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
1996     if (WriteBlob(image,(size_t) count,buffer) != count)
1997       status=MagickFalse;
1998   }
1999   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2000   TIFFClose(tiff);
2001   huffman_image=DestroyImage(huffman_image);
2002   (void) fclose(file);
2003   (void) RelinquishUniqueFileResource(filename);
2004   (void) CloseBlob(image);
2005   return(status);
2006 }
2007 #endif
2008 \f
2009 #if defined(MAGICKCORE_TIFF_DELEGATE)
2010 /*
2011 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2012 %                                                                             %
2013 %                                                                             %
2014 %                                                                             %
2015 %   W r i t e P T I F I m a g e                                               %
2016 %                                                                             %
2017 %                                                                             %
2018 %                                                                             %
2019 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2020 %
2021 %  WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2022 %  format.
2023 %
2024 %  The format of the WritePTIFImage method is:
2025 %
2026 %      MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2027 %        Image *image,ExceptionInfo *exception)
2028 %
2029 %  A description of each parameter follows:
2030 %
2031 %    o image_info: the image info.
2032 %
2033 %    o image:  The image.
2034 %
2035 %    o exception: return any errors or warnings in this structure.
2036 %
2037 */
2038 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2039   Image *image,ExceptionInfo *exception)
2040 {
2041   Image
2042     *images,
2043     *next,
2044     *pyramid_image;
2045
2046   ImageInfo
2047     *write_info;
2048
2049   MagickBooleanType
2050     status;
2051
2052   size_t
2053     columns,
2054     rows;
2055
2056   /*
2057     Create pyramid-encoded TIFF image.
2058   */
2059   images=NewImageList();
2060   for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2061   {
2062     AppendImageToList(&images,CloneImage(next,0,0,MagickFalse,exception));
2063     columns=next->columns;
2064     rows=next->rows;
2065     while ((columns > 64) && (rows > 64))
2066     {
2067       columns/=2;
2068       rows/=2;
2069       pyramid_image=ResizeImage(next,columns,rows,UndefinedFilter,image->blur,
2070         exception);
2071       AppendImageToList(&images,pyramid_image);
2072     }
2073   }
2074   /*
2075     Write pyramid-encoded TIFF image.
2076   */
2077   write_info=CloneImageInfo(image_info);
2078   *write_info->magick='\0';
2079   write_info->adjoin=MagickTrue;
2080   status=WriteTIFFImage(write_info,GetFirstImageInList(images),exception);
2081   images=DestroyImageList(images);
2082   write_info=DestroyImageInfo(write_info);
2083   return(status);
2084 }
2085 #endif
2086 \f
2087 #if defined(MAGICKCORE_TIFF_DELEGATE)
2088 /*
2089 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2090 %                                                                             %
2091 %                                                                             %
2092 %   W r i t e T I F F I m a g e                                               %
2093 %                                                                             %
2094 %                                                                             %
2095 %                                                                             %
2096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2097 %
2098 %  WriteTIFFImage() writes an image in the Tagged image file format.
2099 %
2100 %  The format of the WriteTIFFImage method is:
2101 %
2102 %      MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2103 %        Image *image,ExceptionInfo *exception)
2104 %
2105 %  A description of each parameter follows:
2106 %
2107 %    o image_info: the image info.
2108 %
2109 %    o image:  The image.
2110 %
2111 %    o exception: return any errors or warnings in this structure.
2112 %
2113 */
2114
2115 typedef struct _TIFFInfo
2116 {
2117   RectangleInfo
2118     tile_geometry;
2119
2120   unsigned char
2121     *scanline,
2122     *scanlines,
2123     *pixels;
2124 } TIFFInfo;
2125
2126 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2127 {
2128   assert(tiff_info != (TIFFInfo *) NULL);
2129   if (tiff_info->scanlines != (unsigned char *) NULL)
2130     tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2131       tiff_info->scanlines);
2132   if (tiff_info->pixels != (unsigned char *) NULL)
2133     tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2134       tiff_info->pixels);
2135 }
2136
2137 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
2138   TIFFInfo *tiff_info)
2139 {
2140   const char
2141     *option;
2142
2143   MagickStatusType
2144     flags;
2145
2146   uint32
2147     tile_columns,
2148     tile_rows;
2149
2150   assert(tiff_info != (TIFFInfo *) NULL);
2151   (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2152   option=GetImageOption(image_info,"tiff:tile-geometry");
2153   if (option == (const char *) NULL)
2154     return(MagickTrue);
2155   flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2156   if ((flags & HeightValue) == 0)
2157     tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2158   tile_columns=(uint32) tiff_info->tile_geometry.width;
2159   tile_rows=(uint32) tiff_info->tile_geometry.height;
2160   TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2161   (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2162   (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2163   tiff_info->tile_geometry.width=tile_columns;
2164   tiff_info->tile_geometry.height=tile_rows;
2165   tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2166     tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2167   tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2168     tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2169   if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2170       (tiff_info->pixels == (unsigned char *) NULL))
2171     {
2172       DestroyTIFFInfo(tiff_info);
2173       return(MagickFalse);
2174     }
2175   return(MagickTrue);
2176 }
2177
2178 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2179   tsample_t sample,Image *image)
2180 {
2181   int32
2182     status;
2183
2184   register ssize_t
2185     i;
2186
2187   register unsigned char
2188     *p,
2189     *q;
2190
2191   size_t
2192     number_tiles,
2193     tile_width;
2194
2195   ssize_t
2196     bytes_per_pixel,
2197     j,
2198     k,
2199     l;
2200
2201   if (TIFFIsTiled(tiff) == 0)
2202     return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2203   /*
2204     Fill scanlines to tile height.
2205   */
2206   i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2207   (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2208     (size_t) TIFFScanlineSize(tiff));
2209   if (((size_t) (row % tiff_info->tile_geometry.height) !=
2210       (tiff_info->tile_geometry.height-1)) &&
2211       (row != (ssize_t) (image->rows-1)))
2212     return(0);
2213   /*
2214     Write tile to TIFF image.
2215   */
2216   status=0;
2217   bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
2218     tiff_info->tile_geometry.width);
2219   number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2220     tiff_info->tile_geometry.width;
2221   for (i=0; i < (ssize_t) number_tiles; i++)
2222   {
2223     tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2224       tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2225     for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2226       for (k=0; k < (ssize_t) tile_width; k++)
2227       {
2228         if (bytes_per_pixel == 0)
2229           {
2230             p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2231               tiff_info->tile_geometry.width+k)/8);
2232             q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2233             *q++=(*p++);
2234             continue;
2235           }
2236         p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2237           tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2238         q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2239         for (l=0; l < bytes_per_pixel; l++)
2240           *q++=(*p++);
2241       }
2242     if ((i*tiff_info->tile_geometry.width) != image->columns)
2243       status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2244         tiff_info->tile_geometry.width),(uint32) ((row/
2245         tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2246         sample);
2247     if (status < 0)
2248       break;
2249   }
2250   return(status);
2251 }
2252
2253 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2254 {
2255   const char
2256     *name;
2257
2258   const StringInfo
2259     *profile;
2260
2261   if (image->profiles == (void *) NULL)
2262     return;
2263   ResetImageProfileIterator(image);
2264   for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2265   {
2266     profile=GetImageProfile(image,name);
2267 #if defined(TIFFTAG_XMLPACKET)
2268     if (LocaleCompare(name,"xmp") == 0)
2269       (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2270         profile),GetStringInfoDatum(profile));
2271 #endif
2272 #if defined(TIFFTAG_ICCPROFILE)
2273     if (LocaleCompare(name,"icc") == 0)
2274       (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2275         profile),GetStringInfoDatum(profile));
2276 #endif
2277     if (LocaleCompare(name,"iptc") == 0)
2278       {
2279         size_t
2280           length;
2281
2282         StringInfo
2283           *iptc_profile;
2284
2285         iptc_profile=CloneStringInfo(profile);
2286         length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2287           0x03);
2288         SetStringInfoLength(iptc_profile,length);
2289         if (TIFFIsByteSwapped(tiff))
2290           TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2291             (unsigned long) (length/4));
2292         (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2293           GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2294         iptc_profile=DestroyStringInfo(iptc_profile);
2295       }
2296 #if defined(TIFFTAG_PHOTOSHOP)
2297     if (LocaleCompare(name,"8bim") == 0)
2298       (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2299         GetStringInfoLength(profile),GetStringInfoDatum(profile));
2300 #endif
2301     if (LocaleCompare(name,"tiff:37724") == 0)
2302       (void) TIFFSetField(tiff,37724,(uint32)GetStringInfoLength(profile),
2303         GetStringInfoDatum(profile));
2304     name=GetNextImageProfile(image);
2305   }
2306 }
2307
2308 static void TIFFSetProperties(TIFF *tiff,Image *image)
2309 {
2310   const char
2311     *value;
2312
2313   (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
2314   value=GetImageProperty(image,"tiff:hostcomputer");
2315   if (value != (const char *) NULL)
2316     (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2317   value=GetImageProperty(image,"tiff:artist");
2318   if (value != (const char *) NULL)
2319     (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2320   value=GetImageProperty(image,"tiff:timestamp");
2321   if (value != (const char *) NULL)
2322     (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2323   value=GetImageProperty(image,"tiff:make");
2324   if (value != (const char *) NULL)
2325     (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2326   value=GetImageProperty(image,"tiff:model");
2327   if (value != (const char *) NULL)
2328     (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2329   value=GetImageProperty(image,"tiff:software");
2330   if (value != (const char *) NULL)
2331     (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2332   value=GetImageProperty(image,"tiff:copyright");
2333   if (value != (const char *) NULL)
2334     (void) TIFFSetField(tiff,33432,value);
2335   value=GetImageProperty(image,"kodak-33423");
2336   if (value != (const char *) NULL)
2337     (void) TIFFSetField(tiff,33423,value);
2338   value=GetImageProperty(image,"kodak-36867");
2339   if (value != (const char *) NULL)
2340     (void) TIFFSetField(tiff,36867,value);
2341   value=GetImageProperty(image,"label");
2342   if (value != (const char *) NULL)
2343     (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
2344   value=GetImageProperty(image,"comment");
2345   if (value != (const char *) NULL)
2346     (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
2347 }
2348
2349 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
2350 {
2351 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
2352   const char
2353     *value;
2354
2355   register ssize_t
2356     i;
2357
2358   uint32
2359     offset;
2360
2361   /*
2362     Write EXIF properties.
2363   */
2364   offset=0;
2365   (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
2366   for (i=0; exif_info[i].tag != 0; i++)
2367   {
2368     value=GetImageProperty(image,exif_info[i].property);
2369     if (value == (const char *) NULL)
2370       continue;
2371     switch (exif_info[i].type)
2372     {
2373       case TIFF_ASCII:
2374       {
2375         (void) TIFFSetField(tiff,exif_info[i].tag,value);
2376         break;
2377       }
2378       case TIFF_SHORT:
2379       {
2380         uint16
2381           shorty;
2382
2383         shorty=(uint16) StringToLong(value);
2384         (void) TIFFSetField(tiff,exif_info[i].tag,shorty);
2385         break;
2386       }
2387       case TIFF_LONG:
2388       {
2389         uint16
2390           ssize_ty;
2391
2392         ssize_ty=(uint16) StringToLong(value);
2393         (void) TIFFSetField(tiff,exif_info[i].tag,ssize_ty);
2394         break;
2395       }
2396       case TIFF_RATIONAL:
2397       case TIFF_SRATIONAL:
2398       {
2399         float
2400           rational;
2401
2402         rational=InterpretLocaleValue(value,(char **) NULL);
2403         (void) TIFFSetField(tiff,exif_info[i].tag,rational);
2404         break;
2405       }
2406       default:
2407         break;
2408     }
2409   }
2410   /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
2411 #else
2412   (void) tiff;
2413   (void) image;
2414 #endif
2415 }
2416
2417 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2418   Image *image,ExceptionInfo *exception)
2419 {
2420 #if !defined(TIFFDefaultStripSize)
2421 #define TIFFDefaultStripSize(tiff,request)  (8192UL/TIFFScanlineSize(tiff))
2422 #endif
2423
2424   const char
2425     *mode,
2426     *option;
2427
2428   CompressionType
2429     compression;
2430
2431   EndianType
2432     endian_type;
2433
2434   MagickBooleanType
2435     debug,
2436     status;
2437
2438   MagickOffsetType
2439     scene;
2440
2441   QuantumInfo
2442     *quantum_info;
2443
2444   QuantumType
2445     quantum_type;
2446
2447   register ssize_t
2448     i;
2449
2450   size_t
2451     length,
2452     lsb_first;
2453
2454   ssize_t
2455     y;
2456
2457   TIFF
2458     *tiff;
2459
2460   TIFFErrorHandler
2461     error_handler,
2462     warning_handler;
2463
2464   TIFFInfo
2465     tiff_info;
2466
2467   uint16
2468     bits_per_sample,
2469     compress_tag,
2470     endian,
2471     photometric;
2472
2473   uint32
2474     rows_per_strip;
2475
2476   unsigned char
2477     *pixels;
2478
2479   /*
2480     Open TIFF file.
2481   */
2482   assert(image_info != (const ImageInfo *) NULL);
2483   assert(image_info->signature == MagickSignature);
2484   assert(image != (Image *) NULL);
2485   assert(image->signature == MagickSignature);
2486   if (image->debug != MagickFalse)
2487     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2488   assert(exception != (ExceptionInfo *) NULL);
2489   assert(exception->signature == MagickSignature);
2490   assert(exception != (ExceptionInfo *) NULL);
2491   assert(exception->signature == MagickSignature);
2492   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2493   if (status == MagickFalse)
2494     return(status);
2495   (void) MagickSetThreadValue(tiff_exception,exception);
2496   error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
2497   warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
2498   endian_type=UndefinedEndian;
2499   option=GetImageOption(image_info,"tiff:endian");
2500   if (option != (const char *) NULL)
2501     {
2502       if (LocaleNCompare(option,"msb",3) == 0)
2503         endian_type=MSBEndian;
2504       if (LocaleNCompare(option,"lsb",3) == 0)
2505         endian_type=LSBEndian;;
2506     }
2507   switch (endian_type)
2508   {
2509     case LSBEndian: mode="wl"; break;
2510     case MSBEndian: mode="wb"; break;
2511     default: mode="w"; break;
2512   }
2513 #if defined(TIFF_VERSION_BIG)
2514   if (LocaleCompare(image_info->magick,"TIFF64") == 0)
2515     switch (endian_type)
2516     {
2517       case LSBEndian: mode="wl8"; break;
2518       case MSBEndian: mode="wb8"; break;
2519       default: mode="w8"; break;
2520     }
2521 #endif
2522   tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
2523     TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
2524     TIFFUnmapBlob);
2525   if (tiff == (TIFF *) NULL)
2526     {
2527       (void) TIFFSetWarningHandler(warning_handler);
2528       (void) TIFFSetErrorHandler(error_handler);
2529       return(MagickFalse);
2530     }
2531   scene=0;
2532   debug=IsEventLogging();
2533   (void) debug;
2534   do
2535   {
2536     /*
2537       Initialize TIFF fields.
2538     */
2539     if ((image_info->type != UndefinedType) &&
2540         (image_info->type != OptimizeType))
2541       (void) SetImageType(image,image_info->type);
2542     quantum_info=AcquireQuantumInfo(image_info,image);
2543     if (quantum_info == (QuantumInfo *) NULL)
2544       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2545     if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
2546         (quantum_info->format == UndefinedQuantumFormat) &&
2547         (IsHighDynamicRangeImage(image,exception) != MagickFalse))
2548       {
2549         status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
2550         if (status == MagickFalse)
2551           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2552       }
2553     if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
2554         (GetPreviousImageInList(image) != (Image *) NULL))
2555       (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
2556     if ((image->columns != (uint32) image->columns) ||
2557         (image->rows != (uint32) image->rows))
2558       ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
2559     (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
2560     (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
2561     compression=image->compression;
2562     if (image_info->compression != UndefinedCompression)
2563       compression=image_info->compression;
2564     switch (compression)
2565     {
2566       case FaxCompression:
2567       {
2568         compress_tag=COMPRESSION_CCITTFAX3;
2569         SetQuantumMinIsWhite(quantum_info,MagickTrue);
2570         break;
2571       }
2572       case Group4Compression:
2573       {
2574         compress_tag=COMPRESSION_CCITTFAX4;
2575         SetQuantumMinIsWhite(quantum_info,MagickTrue);
2576         break;
2577       }
2578 #if defined(COMPRESSION_JBIG)
2579       case JBIG1Compression:
2580       {
2581         compress_tag=COMPRESSION_JBIG;
2582         break;
2583       }
2584 #endif
2585       case JPEGCompression:
2586       {
2587         compress_tag=COMPRESSION_JPEG;
2588         break;
2589       }
2590 #if defined(COMPRESSION_LZMA)
2591       case LZMACompression:
2592       {
2593         compress_tag=COMPRESSION_LZMA;
2594         break;
2595       }
2596 #endif
2597       case LZWCompression:
2598       {
2599         compress_tag=COMPRESSION_LZW;
2600         break;
2601       }
2602       case RLECompression:
2603       {
2604         compress_tag=COMPRESSION_PACKBITS;
2605         break;
2606       }
2607       case ZipCompression:
2608       {
2609         compress_tag=COMPRESSION_ADOBE_DEFLATE;
2610         break;
2611       }
2612       case NoCompression:
2613       default:
2614       {
2615         compress_tag=COMPRESSION_NONE;
2616         break;
2617       }
2618     }
2619 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
2620     if ((compress_tag != COMPRESSION_NONE) &&
2621         (TIFFIsCODECConfigured(compress_tag) == 0))
2622       {
2623         (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2624           "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2625           MagickCompressOptions,(ssize_t) compression));
2626         compress_tag=COMPRESSION_NONE;
2627         compression=NoCompression;
2628       }
2629 #else
2630       switch (compress_tag)
2631       {
2632 #if defined(CCITT_SUPPORT)
2633         case COMPRESSION_CCITTFAX3:
2634         case COMPRESSION_CCITTFAX4:
2635 #endif
2636 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
2637         case COMPRESSION_JPEG:
2638 #endif
2639 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2640         case COMPRESSION_LZMA:
2641 #endif
2642 #if defined(LZW_SUPPORT)
2643         case COMPRESSION_LZW:
2644 #endif
2645 #if defined(PACKBITS_SUPPORT)
2646         case COMPRESSION_PACKBITS:
2647 #endif
2648 #if defined(ZIP_SUPPORT)
2649         case COMPRESSION_ADOBE_DEFLATE:
2650 #endif
2651         case COMPRESSION_NONE:
2652           break;
2653         default:
2654         {
2655           (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2656             "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2657               MagickCompressOptions,(ssize_t) compression));
2658           compress_tag=COMPRESSION_NONE;
2659           compression=NoCompression;
2660           break;
2661         }
2662       }
2663 #endif
2664     switch (compression)
2665     {
2666       case FaxCompression:
2667       case Group4Compression:
2668       {
2669         (void) SetImageType(image,BilevelType);
2670         break;
2671       }
2672       case JPEGCompression:
2673       {
2674         (void) SetImageStorageClass(image,DirectClass,exception);
2675         (void) SetImageDepth(image,8);
2676         break;
2677       }
2678       default:
2679         break;
2680     }
2681     if (image->colorspace == CMYKColorspace)
2682       {
2683         photometric=PHOTOMETRIC_SEPARATED;
2684         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
2685         (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
2686       }
2687     else
2688       {
2689         /*
2690           Full color TIFF raster.
2691         */
2692         if (image->colorspace == LabColorspace)
2693           photometric=PHOTOMETRIC_CIELAB;
2694         else
2695           if (image->colorspace == YCbCrColorspace)
2696             {
2697               photometric=PHOTOMETRIC_YCBCR;
2698               (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
2699               (void) SetImageStorageClass(image,DirectClass,exception);
2700               (void) SetImageDepth(image,8);
2701             }
2702           else
2703             {
2704               if (IsRGBColorspace(image->colorspace) == MagickFalse)
2705                 (void) TransformImageColorspace(image,RGBColorspace);
2706               photometric=PHOTOMETRIC_RGB;
2707             }
2708         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
2709         if ((image_info->type != TrueColorType) &&
2710             (image_info->type != TrueColorMatteType))
2711           {
2712             if ((image_info->type != PaletteType) &&
2713                 (IsImageGray(image,exception) != MagickFalse))
2714               {
2715                 photometric=(uint16) (quantum_info->min_is_white !=
2716                   MagickFalse ? PHOTOMETRIC_MINISWHITE :
2717                   PHOTOMETRIC_MINISBLACK);
2718                 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2719                 if ((image_info->depth == 0) && (image->matte == MagickFalse) &&
2720                     (IsImageMonochrome(image,exception) != MagickFalse))
2721                   {
2722                     status=SetQuantumDepth(image,quantum_info,1);
2723                     if (status == MagickFalse)
2724                       ThrowWriterException(ResourceLimitError,
2725                         "MemoryAllocationFailed");
2726                   }
2727               }
2728             else
2729               if (image->storage_class == PseudoClass)
2730                 {
2731                   size_t
2732                     depth;
2733
2734                   /*
2735                     Colormapped TIFF raster.
2736                   */
2737                   (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2738                   photometric=PHOTOMETRIC_PALETTE;
2739                   depth=1;
2740                   while ((GetQuantumRange(depth)+1) < image->colors)
2741                     depth<<=1;
2742                   status=SetQuantumDepth(image,quantum_info,depth);
2743                   if (status == MagickFalse)
2744                     ThrowWriterException(ResourceLimitError,
2745                       "MemoryAllocationFailed");
2746                 }
2747           }
2748       }
2749     switch (image->endian)
2750     {
2751       case LSBEndian:
2752       {
2753         endian=FILLORDER_LSB2MSB;
2754         break;
2755       }
2756       case MSBEndian:
2757       {
2758         endian=FILLORDER_MSB2LSB;
2759         break;
2760       }
2761       case UndefinedEndian:
2762       default:
2763       {
2764         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
2765         break;
2766       }
2767     }
2768     lsb_first=1;
2769     image->endian=MSBEndian;
2770     if ((int) (*(char *) &lsb_first) != 0)
2771       image->endian=LSBEndian;
2772     if ((compress_tag == COMPRESSION_CCITTFAX3) &&
2773         (photometric != PHOTOMETRIC_MINISWHITE))
2774       {
2775         compress_tag=COMPRESSION_NONE;
2776         endian=FILLORDER_MSB2LSB;
2777       }
2778     else
2779       if ((compress_tag == COMPRESSION_CCITTFAX4) &&
2780          (photometric != PHOTOMETRIC_MINISWHITE))
2781        {
2782          compress_tag=COMPRESSION_NONE;
2783          endian=FILLORDER_MSB2LSB;
2784        }
2785     option=GetImageProperty(image,"tiff:fill-order");
2786     if (option != (const char *) NULL)
2787       {
2788         if (LocaleNCompare(option,"msb",3) == 0)
2789           endian=FILLORDER_MSB2LSB;
2790         if (LocaleNCompare(option,"lsb",3) == 0)
2791           endian=FILLORDER_LSB2MSB;
2792       }
2793     (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
2794     (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
2795     (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
2796     if (image->matte != MagickFalse)
2797       {
2798         uint16
2799           extra_samples,
2800           sample_info[1],
2801           samples_per_pixel;
2802
2803         /*
2804           TIFF has a matte channel.
2805         */
2806         extra_samples=1;
2807         sample_info[0]=EXTRASAMPLE_UNASSALPHA;
2808         option=GetImageProperty(image,"tiff:alpha");
2809         if ((option != (const char *) NULL) &&
2810             (LocaleCompare(option,"associated") == 0))
2811           sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
2812         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
2813           &samples_per_pixel);
2814         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
2815         (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
2816           &sample_info);
2817         if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
2818           SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
2819       }
2820     (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
2821     switch (quantum_info->format)
2822     {
2823       case FloatingPointQuantumFormat:
2824       {
2825         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
2826         (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
2827         (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
2828         break;
2829       }
2830       case SignedQuantumFormat:
2831       {
2832         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
2833         break;
2834       }
2835       case UnsignedQuantumFormat:
2836       {
2837         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
2838         break;
2839       }
2840       default:
2841         break;
2842     }
2843     (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
2844     (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
2845     if (photometric == PHOTOMETRIC_RGB)
2846       if ((image_info->interlace == PlaneInterlace) ||
2847           (image_info->interlace == PartitionInterlace))
2848         (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
2849     rows_per_strip=1;
2850     if (TIFFScanlineSize(tiff) != 0)
2851       rows_per_strip=(uint32) MagickMax((size_t) TIFFDefaultStripSize(tiff,0),
2852         1);
2853     option=GetImageOption(image_info,"tiff:rows-per-strip");
2854     if (option != (const char *) NULL)
2855       rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
2856     switch (compress_tag)
2857     {
2858       case COMPRESSION_JPEG:
2859       {
2860 #if defined(JPEG_SUPPORT)
2861         const char
2862           *sampling_factor;
2863
2864         GeometryInfo
2865           geometry_info;
2866
2867         MagickStatusType
2868           flags;
2869
2870         rows_per_strip+=(16-(rows_per_strip % 16));
2871         if (image->quality != 0)
2872           (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image->quality);
2873         if (image_info->quality != UndefinedCompressionQuality)
2874           (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
2875         (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
2876         if (IsRGBColorspace(image->colorspace) == MagickTrue)
2877           {
2878             const char
2879               *value;
2880
2881             (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
2882             sampling_factor=(const char *) NULL;
2883             value=GetImageProperty(image,"jpeg:sampling-factor");
2884             if (value != (char *) NULL)
2885               {
2886                 sampling_factor=value;
2887                 if (image->debug != MagickFalse)
2888                   (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2889                     "  Input sampling-factors=%s",sampling_factor);
2890               }
2891             if (image_info->sampling_factor != (char *) NULL)
2892               sampling_factor=image_info->sampling_factor;
2893             if (sampling_factor != (const char *) NULL)
2894               {
2895                 flags=ParseGeometry(sampling_factor,&geometry_info);
2896                 if ((flags & SigmaValue) == 0)
2897                   geometry_info.sigma=geometry_info.rho;
2898                 if (image->colorspace == YCbCrColorspace)
2899                   (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
2900                     geometry_info.rho,(uint16) geometry_info.sigma);
2901               }
2902           }
2903         if (bits_per_sample == 12)
2904           (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
2905 #endif
2906         break;
2907       }
2908       case COMPRESSION_ADOBE_DEFLATE:
2909       {
2910         rows_per_strip=(uint32) image->rows;
2911         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
2912           &bits_per_sample);
2913         if (((photometric == PHOTOMETRIC_RGB) ||
2914              (photometric == PHOTOMETRIC_MINISBLACK)) &&
2915             ((bits_per_sample == 8) || (bits_per_sample == 16)))
2916           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2917         (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
2918           image_info->quality == UndefinedCompressionQuality ? 7 :
2919           MagickMin((ssize_t) image_info->quality/10,9)));
2920         break;
2921       }
2922       case COMPRESSION_CCITTFAX3:
2923       {
2924         /*
2925           Byte-aligned EOL.
2926         */
2927         rows_per_strip=(uint32) image->rows;
2928         (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
2929         break;
2930       }
2931       case COMPRESSION_CCITTFAX4:
2932       {
2933         rows_per_strip=(uint32) image->rows;
2934         break;
2935       }
2936 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2937       case COMPRESSION_LZMA:
2938       {
2939         if (((photometric == PHOTOMETRIC_RGB) ||
2940              (photometric == PHOTOMETRIC_MINISBLACK)) &&
2941             ((bits_per_sample == 8) || (bits_per_sample == 16)))
2942           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2943         (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
2944           image_info->quality == UndefinedCompressionQuality ? 7 :
2945           MagickMin((ssize_t) image_info->quality/10,9)));
2946         break;
2947       }
2948 #endif
2949       case COMPRESSION_LZW:
2950       {
2951         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
2952           &bits_per_sample);
2953         if (((photometric == PHOTOMETRIC_RGB) ||
2954              (photometric == PHOTOMETRIC_MINISBLACK)) &&
2955             ((bits_per_sample == 8) || (bits_per_sample == 16)))
2956           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2957         break;
2958       }
2959       default:
2960         break;
2961     }
2962     option=GetImageOption(image_info,"tiff:tile-geometry");
2963     if (option == (const char *) NULL)
2964       (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
2965     if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
2966       {
2967         unsigned short
2968           units;
2969
2970         /*
2971           Set image resolution.
2972         */
2973         units=RESUNIT_NONE;
2974         if (image->units == PixelsPerInchResolution)
2975           units=RESUNIT_INCH;
2976         if (image->units == PixelsPerCentimeterResolution)
2977           units=RESUNIT_CENTIMETER;
2978         (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
2979         (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
2980         (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
2981         if ((image->page.x != 0) || (image->page.y != 0))
2982           {
2983             /*
2984               Set image position.
2985             */
2986             (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
2987               image->x_resolution);
2988             (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
2989               image->y_resolution);
2990           }
2991       }
2992     if (image->chromaticity.white_point.x != 0.0)
2993       {
2994         float
2995           chromaticity[6];
2996
2997         /*
2998           Set image chromaticity.
2999         */
3000         chromaticity[0]=(float) image->chromaticity.red_primary.x;
3001         chromaticity[1]=(float) image->chromaticity.red_primary.y;
3002         chromaticity[2]=(float) image->chromaticity.green_primary.x;
3003         chromaticity[3]=(float) image->chromaticity.green_primary.y;
3004         chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3005         chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3006         (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3007         chromaticity[0]=(float) image->chromaticity.white_point.x;
3008         chromaticity[1]=(float) image->chromaticity.white_point.y;
3009         (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3010       }
3011     if ((image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3012       {
3013         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3014         if (image->scene != 0)
3015           (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3016             GetImageListLength(image));
3017       }
3018     if (image->orientation != UndefinedOrientation)
3019       (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3020     (void) TIFFSetProfiles(tiff,image);
3021     {
3022       uint16
3023         page,
3024         pages;
3025
3026       page=(uint16) scene;
3027       pages=(uint16) GetImageListLength(image);
3028       if ((image_info->adjoin != MagickFalse) && (pages > 1))
3029         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3030       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3031     }
3032     (void) TIFFSetProperties(tiff,image);
3033     if (0)
3034       (void) TIFFSetEXIFProperties(tiff,image);
3035     /*
3036       Write image scanlines.
3037     */
3038     if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3039       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3040     pixels=GetQuantumPixels(quantum_info);
3041     tiff_info.scanline=GetQuantumPixels(quantum_info);
3042     switch (photometric)
3043     {
3044       case PHOTOMETRIC_CIELAB:
3045       case PHOTOMETRIC_YCBCR:
3046       case PHOTOMETRIC_RGB:
3047       {
3048         /*
3049           RGB TIFF image.
3050         */
3051         switch (image_info->interlace)
3052         {
3053           case NoInterlace:
3054           default:
3055           {
3056             quantum_type=RGBQuantum;
3057             if (image->matte != MagickFalse)
3058               quantum_type=RGBAQuantum;
3059             for (y=0; y < (ssize_t) image->rows; y++)
3060             {
3061               register const Quantum
3062                 *restrict p;
3063
3064               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3065               if (p == (const Quantum *) NULL)
3066                 break;
3067               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3068                 quantum_type,pixels,exception);
3069               (void) length;
3070               if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3071                 break;
3072               if (image->previous == (Image *) NULL)
3073                 {
3074                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3075                     y,image->rows);
3076                   if (status == MagickFalse)
3077                     break;
3078                 }
3079             }
3080             break;
3081           }
3082           case PlaneInterlace:
3083           case PartitionInterlace:
3084           {
3085             /*
3086               Plane interlacing:  RRRRRR...GGGGGG...BBBBBB...
3087             */
3088             for (y=0; y < (ssize_t) image->rows; y++)
3089             {
3090               register const Quantum
3091                 *restrict p;
3092
3093               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3094               if (p == (const Quantum *) NULL)
3095                 break;
3096               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3097                 RedQuantum,pixels,exception);
3098               if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3099                 break;
3100             }
3101             if (image->previous == (Image *) NULL)
3102               {
3103                 status=SetImageProgress(image,SaveImageTag,100,400);
3104                 if (status == MagickFalse)
3105                   break;
3106               }
3107             for (y=0; y < (ssize_t) image->rows; y++)
3108             {
3109               register const Quantum
3110                 *restrict p;
3111
3112               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3113               if (p == (const Quantum *) NULL)
3114                 break;
3115               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3116                 GreenQuantum,pixels,exception);
3117               if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3118                 break;
3119             }
3120             if (image->previous == (Image *) NULL)
3121               {
3122                 status=SetImageProgress(image,SaveImageTag,200,400);
3123                 if (status == MagickFalse)
3124                   break;
3125               }
3126             for (y=0; y < (ssize_t) image->rows; y++)
3127             {
3128               register const Quantum
3129                 *restrict p;
3130
3131               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3132               if (p == (const Quantum *) NULL)
3133                 break;
3134               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3135                 BlueQuantum,pixels,exception);
3136               if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3137                 break;
3138             }
3139             if (image->previous == (Image *) NULL)
3140               {
3141                 status=SetImageProgress(image,SaveImageTag,300,400);
3142                 if (status == MagickFalse)
3143                   break;
3144               }
3145             if (image->matte != MagickFalse)
3146               for (y=0; y < (ssize_t) image->rows; y++)
3147               {
3148                 register const Quantum
3149                   *restrict p;
3150
3151                 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3152                 if (p == (const Quantum *) NULL)
3153                   break;
3154                 length=ExportQuantumPixels(image,(CacheView *) NULL,
3155                   quantum_info,AlphaQuantum,pixels,exception);
3156                 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3157                   break;
3158               }
3159             if (image->previous == (Image *) NULL)
3160               {
3161                 status=SetImageProgress(image,SaveImageTag,400,400);
3162                 if (status == MagickFalse)
3163                   break;
3164               }
3165             break;
3166           }
3167         }
3168         break;
3169       }
3170       case PHOTOMETRIC_SEPARATED:
3171       {
3172         /*
3173           CMYK TIFF image.
3174         */
3175         quantum_type=CMYKQuantum;
3176         if (image->matte != MagickFalse)
3177           quantum_type=CMYKAQuantum;
3178         if (image->colorspace != CMYKColorspace)
3179           (void) TransformImageColorspace(image,CMYKColorspace);
3180         for (y=0; y < (ssize_t) image->rows; y++)
3181         {
3182           register const Quantum
3183             *restrict p;
3184
3185           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3186           if (p == (const Quantum *) NULL)
3187             break;
3188           length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3189             quantum_type,pixels,exception);
3190           if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3191             break;
3192           if (image->previous == (Image *) NULL)
3193             {
3194               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3195                 image->rows);
3196               if (status == MagickFalse)
3197                 break;
3198             }
3199         }
3200         break;
3201       }
3202       case PHOTOMETRIC_PALETTE:
3203       {
3204         uint16
3205           *blue,
3206           *green,
3207           *red;
3208
3209         /*
3210           Colormapped TIFF image.
3211         */
3212         red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3213         green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3214         blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3215         if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3216             (blue == (uint16 *) NULL))
3217           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3218         /*
3219           Initialize TIFF colormap.
3220         */
3221         (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3222         (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3223         (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3224         for (i=0; i < (ssize_t) image->colors; i++)
3225         {
3226           red[i]=ScaleQuantumToShort(image->colormap[i].red);
3227           green[i]=ScaleQuantumToShort(image->colormap[i].green);
3228           blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3229         }
3230         (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3231         red=(uint16 *) RelinquishMagickMemory(red);
3232         green=(uint16 *) RelinquishMagickMemory(green);
3233         blue=(uint16 *) RelinquishMagickMemory(blue);
3234       }
3235       default:
3236       {
3237         /*
3238           Convert PseudoClass packets to contiguous grayscale scanlines.
3239         */
3240         quantum_type=IndexQuantum;
3241         if (image->matte != MagickFalse)
3242           {
3243             if (photometric != PHOTOMETRIC_PALETTE)
3244               quantum_type=GrayAlphaQuantum;
3245             else
3246               quantum_type=IndexAlphaQuantum;
3247            }
3248          else
3249            if (photometric != PHOTOMETRIC_PALETTE)
3250              quantum_type=GrayQuantum;
3251         for (y=0; y < (ssize_t) image->rows; y++)
3252         {
3253           register const Quantum
3254             *restrict p;
3255
3256           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3257           if (p == (const Quantum *) NULL)
3258             break;
3259           length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3260             quantum_type,pixels,exception);
3261           if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3262             break;
3263           if (image->previous == (Image *) NULL)
3264             {
3265               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3266                 image->rows);
3267               if (status == MagickFalse)
3268                 break;
3269             }
3270         }
3271         break;
3272       }
3273     }
3274     quantum_info=DestroyQuantumInfo(quantum_info);
3275     DestroyTIFFInfo(&tiff_info);
3276     if (0 && (image_info->verbose == MagickTrue))
3277       TIFFPrintDirectory(tiff,stdout,MagickFalse);
3278     (void) TIFFWriteDirectory(tiff);
3279     image->endian=MSBEndian;
3280     if (endian == FILLORDER_LSB2MSB)
3281       image->endian=LSBEndian;
3282     image=SyncNextImageInList(image);
3283     if (image == (Image *) NULL)
3284       break;
3285     status=SetImageProgress(image,SaveImagesTag,scene++,
3286       GetImageListLength(image));
3287     if (status == MagickFalse)
3288       break;
3289   } while (image_info->adjoin != MagickFalse);
3290   (void) TIFFSetWarningHandler(warning_handler);
3291   (void) TIFFSetErrorHandler(error_handler);
3292   TIFFClose(tiff);
3293   return(MagickTrue);
3294 }
3295 #endif