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