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