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