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