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