]> granicus.if.org Git - imagemagick/blob - coders/tiff.c
https://github.com/ImageMagick/ImageMagick/issues/298
[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-2016 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     *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 >= 2) && (interlace == PLANARCONFIG_CONTIG))
1587       method=ReadRGBAMethod;
1588     if ((samples_per_pixel >= 2) && (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     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1612     switch (method)
1613     {
1614       case ReadSingleSampleMethod:
1615       {
1616         /*
1617           Convert TIFF image to PseudoClass MIFF image.
1618         */
1619         quantum_type=IndexQuantum;
1620         pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1621         if (image->alpha_trait != UndefinedPixelTrait)
1622           {
1623             if (image->storage_class != PseudoClass)
1624               {
1625                 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1626                   GrayAlphaQuantum;
1627                 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1628               }
1629             else
1630               {
1631                 quantum_type=IndexAlphaQuantum;
1632                 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1633               }
1634           }
1635         else
1636           if (image->storage_class != PseudoClass)
1637             {
1638               quantum_type=GrayQuantum;
1639               pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1640             }
1641         status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
1642           bits_per_sample)/log(2))));
1643         if (status == MagickFalse)
1644           {
1645             TIFFClose(tiff);
1646             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1647           }
1648         pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1649         for (y=0; y < (ssize_t) image->rows; y++)
1650         {
1651           int
1652             status;
1653
1654           register Quantum
1655             *magick_restrict q;
1656
1657           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1658           if (status == -1)
1659             break;
1660           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1661           if (q == (Quantum *) NULL)
1662             break;
1663           (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1664             quantum_type,pixels,exception);
1665           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1666             break;
1667           if (image->previous == (Image *) NULL)
1668             {
1669               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1670                 image->rows);
1671               if (status == MagickFalse)
1672                 break;
1673             }
1674         }
1675         break;
1676       }
1677       case ReadRGBAMethod:
1678       {
1679         /*
1680           Convert TIFF image to DirectClass MIFF image.
1681         */
1682         pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1683         quantum_type=RGBQuantum;
1684         if (image->alpha_trait != UndefinedPixelTrait)
1685           {
1686             quantum_type=RGBAQuantum;
1687             pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1688           }
1689         if (image->colorspace == CMYKColorspace)
1690           {
1691             pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1692             quantum_type=CMYKQuantum;
1693             if (image->alpha_trait != UndefinedPixelTrait)
1694               {
1695                 quantum_type=CMYKAQuantum;
1696                 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1697               }
1698           }
1699         status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1700         if (status == MagickFalse)
1701           {
1702             TIFFClose(tiff);
1703             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1704           }
1705         pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1706         for (y=0; y < (ssize_t) image->rows; y++)
1707         {
1708           int
1709             status;
1710
1711           register Quantum
1712             *magick_restrict q;
1713
1714           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1715           if (status == -1)
1716             break;
1717           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1718           if (q == (Quantum *) NULL)
1719             break;
1720           (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1721             quantum_type,pixels,exception);
1722           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1723             break;
1724           if (image->previous == (Image *) NULL)
1725             {
1726               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1727                 image->rows);
1728               if (status == MagickFalse)
1729                 break;
1730             }
1731         }
1732         break;
1733       }
1734       case ReadCMYKAMethod:
1735       {
1736         /*
1737           Convert TIFF image to DirectClass MIFF image.
1738         */
1739         for (i=0; i < (ssize_t) samples_per_pixel; i++)
1740         {
1741           for (y=0; y < (ssize_t) image->rows; y++)
1742           {
1743             register Quantum
1744               *magick_restrict q;
1745
1746             int
1747               status;
1748
1749             status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1750               pixels);
1751             if (status == -1)
1752               break;
1753             q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1754             if (q == (Quantum *) NULL)
1755               break;
1756             if (image->colorspace != CMYKColorspace)
1757               switch (i)
1758               {
1759                 case 0: quantum_type=RedQuantum; break;
1760                 case 1: quantum_type=GreenQuantum; break;
1761                 case 2: quantum_type=BlueQuantum; break;
1762                 case 3: quantum_type=AlphaQuantum; break;
1763                 default: quantum_type=UndefinedQuantum; break;
1764               }
1765             else
1766               switch (i)
1767               {
1768                 case 0: quantum_type=CyanQuantum; break;
1769                 case 1: quantum_type=MagentaQuantum; break;
1770                 case 2: quantum_type=YellowQuantum; break;
1771                 case 3: quantum_type=BlackQuantum; break;
1772                 case 4: quantum_type=AlphaQuantum; break;
1773                 default: quantum_type=UndefinedQuantum; break;
1774               }
1775             (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1776               quantum_type,pixels,exception);
1777             if (SyncAuthenticPixels(image,exception) == MagickFalse)
1778               break;
1779           }
1780           if (image->previous == (Image *) NULL)
1781             {
1782               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1783                 image->rows);
1784               if (status == MagickFalse)
1785                 break;
1786             }
1787         }
1788         break;
1789       }
1790       case ReadYCCKMethod:
1791       {
1792         pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1793         for (y=0; y < (ssize_t) image->rows; y++)
1794         {
1795           int
1796             status;
1797
1798           register Quantum
1799             *magick_restrict q;
1800
1801           register ssize_t
1802             x;
1803
1804           unsigned char
1805             *p;
1806
1807           status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1808           if (status == -1)
1809             break;
1810           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1811           if (q == (Quantum *) NULL)
1812             break;
1813           p=pixels;
1814           for (x=0; x < (ssize_t) image->columns; x++)
1815           {
1816             SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
1817               (1.402*(double) *(p+2))-179.456)),q);
1818             SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-
1819               (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
1820               135.45984)),q);
1821             SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+
1822               (1.772*(double) *(p+1))-226.816)),q);
1823             SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);
1824             q+=GetPixelChannels(image);
1825             p+=4;
1826           }
1827           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1828             break;
1829           if (image->previous == (Image *) NULL)
1830             {
1831               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1832                 image->rows);
1833               if (status == MagickFalse)
1834                 break;
1835             }
1836         }
1837         break;
1838       }
1839       case ReadStripMethod:
1840       {
1841         register uint32
1842           *p;
1843
1844         /*
1845           Convert stripped TIFF image to DirectClass MIFF image.
1846         */
1847         i=0;
1848         p=(uint32 *) NULL;
1849         for (y=0; y < (ssize_t) image->rows; y++)
1850         {
1851           register ssize_t
1852             x;
1853
1854           register Quantum
1855             *magick_restrict q;
1856
1857           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1858           if (q == (Quantum *) NULL)
1859             break;
1860           if (i == 0)
1861             {
1862               if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1863                 break;
1864               i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1865                 image->rows-y);
1866             }
1867           i--;
1868           p=((uint32 *) pixels)+image->columns*i;
1869           for (x=0; x < (ssize_t) image->columns; x++)
1870           {
1871             SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1872               (TIFFGetR(*p))),q);
1873             SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1874               (TIFFGetG(*p))),q);
1875             SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1876               (TIFFGetB(*p))),q);
1877             if (image->alpha_trait != UndefinedPixelTrait)
1878               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1879                 (TIFFGetA(*p))),q);
1880             p++;
1881             q+=GetPixelChannels(image);
1882           }
1883           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1884             break;
1885           if (image->previous == (Image *) NULL)
1886             {
1887               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1888                 image->rows);
1889               if (status == MagickFalse)
1890                 break;
1891             }
1892         }
1893         break;
1894       }
1895       case ReadTileMethod:
1896       {
1897         register uint32
1898           *p;
1899
1900         uint32
1901           *tile_pixels,
1902           columns,
1903           rows;
1904
1905         /*
1906           Convert tiled TIFF image to DirectClass MIFF image.
1907         */
1908         if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
1909             (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
1910           {
1911             TIFFClose(tiff);
1912             ThrowReaderException(CoderError,"ImageIsNotTiled");
1913           }
1914         (void) SetImageStorageClass(image,DirectClass,exception);
1915         number_pixels=(MagickSizeType) columns*rows;
1916         if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
1917           {
1918             TIFFClose(tiff);
1919             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1920           }
1921         tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
1922           sizeof(*tile_pixels));
1923         if (tile_pixels == (uint32 *) NULL)
1924           {
1925             TIFFClose(tiff);
1926             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1927           }
1928         for (y=0; y < (ssize_t) image->rows; y+=rows)
1929         {
1930           register ssize_t
1931             x;
1932
1933           register Quantum
1934             *magick_restrict q,
1935             *magick_restrict tile;
1936
1937           size_t
1938             columns_remaining,
1939             rows_remaining;
1940
1941           rows_remaining=image->rows-y;
1942           if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1943             rows_remaining=rows;
1944           tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1945             exception);
1946           if (tile == (Quantum *) NULL)
1947             break;
1948           for (x=0; x < (ssize_t) image->columns; x+=columns)
1949           {
1950             size_t
1951               column,
1952               row;
1953
1954             if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1955               break;
1956             columns_remaining=image->columns-x;
1957             if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1958               columns_remaining=columns;
1959             p=tile_pixels+(rows-rows_remaining)*columns;
1960             q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1961               x);
1962             for (row=rows_remaining; row > 0; row--)
1963             {
1964               if (image->alpha_trait != UndefinedPixelTrait)
1965                 for (column=columns_remaining; column > 0; column--)
1966                 {
1967                   SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1968                     TIFFGetR(*p)),q);
1969                   SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1970                     TIFFGetG(*p)),q);
1971                   SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1972                     TIFFGetB(*p)),q);
1973                   SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1974                     TIFFGetA(*p)),q);
1975                   p++;
1976                   q+=GetPixelChannels(image);
1977                 }
1978               else
1979                 for (column=columns_remaining; column > 0; column--)
1980                 {
1981                   SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1982                     TIFFGetR(*p)),q);
1983                   SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1984                     TIFFGetG(*p)),q);
1985                   SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1986                     TIFFGetB(*p)),q);
1987                   p++;
1988                   q+=GetPixelChannels(image);
1989                 }
1990               p+=columns-columns_remaining;
1991               q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1992             }
1993           }
1994           if (SyncAuthenticPixels(image,exception) == MagickFalse)
1995             break;
1996           if (image->previous == (Image *) NULL)
1997             {
1998               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1999                 image->rows);
2000               if (status == MagickFalse)
2001                 break;
2002             }
2003         }
2004         tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
2005         break;
2006       }
2007       case ReadGenericMethod:
2008       default:
2009       {
2010         MemoryInfo
2011           *pixel_info;
2012
2013         register uint32
2014           *p;
2015
2016         uint32
2017           *pixels;
2018
2019         /*
2020           Convert TIFF image to DirectClass MIFF image.
2021         */
2022         number_pixels=(MagickSizeType) image->columns*image->rows;
2023         if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
2024           {
2025             TIFFClose(tiff);
2026             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
2027           }
2028         pixel_info=AcquireVirtualMemory(image->columns,image->rows*
2029           sizeof(uint32));
2030         if (pixel_info == (MemoryInfo *) NULL)
2031           {
2032             TIFFClose(tiff);
2033             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
2034           }
2035         pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
2036         (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
2037           image->rows,(uint32 *) pixels,0);
2038         /*
2039           Convert image to DirectClass pixel packets.
2040         */
2041         p=pixels+number_pixels-1;
2042         for (y=0; y < (ssize_t) image->rows; y++)
2043         {
2044           register ssize_t
2045             x;
2046
2047           register Quantum
2048             *magick_restrict q;
2049
2050           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
2051           if (q == (Quantum *) NULL)
2052             break;
2053           q+=GetPixelChannels(image)*(image->columns-1);
2054           for (x=0; x < (ssize_t) image->columns; x++)
2055           {
2056             SetPixelRed(image,ScaleCharToQuantum((unsigned char)
2057               TIFFGetR(*p)),q);
2058             SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
2059               TIFFGetG(*p)),q);
2060             SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
2061               TIFFGetB(*p)),q);
2062             if (image->alpha_trait != UndefinedPixelTrait)
2063               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
2064                 TIFFGetA(*p)),q);
2065             p--;
2066             q-=GetPixelChannels(image);
2067           }
2068           if (SyncAuthenticPixels(image,exception) == MagickFalse)
2069             break;
2070           if (image->previous == (Image *) NULL)
2071             {
2072               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2073                 image->rows);
2074               if (status == MagickFalse)
2075                 break;
2076             }
2077         }
2078         pixel_info=RelinquishVirtualMemory(pixel_info);
2079         break;
2080       }
2081     }
2082     SetQuantumImageType(image,quantum_type);
2083   next_tiff_frame:
2084     if (quantum_info != (QuantumInfo *) NULL)
2085       quantum_info=DestroyQuantumInfo(quantum_info);
2086     if (photometric == PHOTOMETRIC_CIELAB)
2087       DecodeLabImage(image,exception);
2088     if ((photometric == PHOTOMETRIC_LOGL) ||
2089         (photometric == PHOTOMETRIC_MINISBLACK) ||
2090         (photometric == PHOTOMETRIC_MINISWHITE))
2091       {
2092         image->type=GrayscaleType;
2093         if (bits_per_sample == 1)
2094           image->type=BilevelType;
2095       }
2096     /*
2097       Proceed to next image.
2098     */
2099     if (image_info->number_scenes != 0)
2100       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
2101         break;
2102     status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
2103     if (status != MagickFalse)
2104       {
2105         /*
2106           Allocate next image structure.
2107         */
2108         AcquireNextImage(image_info,image,exception);
2109         if (GetNextImageInList(image) == (Image *) NULL)
2110           {
2111             image=DestroyImageList(image);
2112             return((Image *) NULL);
2113           }
2114         image=SyncNextImageInList(image);
2115         status=SetImageProgress(image,LoadImagesTag,image->scene-1,
2116           image->scene);
2117         if (status == MagickFalse)
2118           break;
2119       }
2120   } while (status != MagickFalse);
2121   TIFFClose(tiff);
2122   TIFFReadPhotoshopLayers(image,image_info,exception);
2123   if (image_info->number_scenes != 0)
2124     {
2125       if (image_info->scene >= GetImageListLength(image))
2126         {
2127           /* Subimage was not found in the Photoshop layer */
2128           image=DestroyImageList(image);
2129           return((Image *)NULL);
2130         }
2131     }
2132   return(GetFirstImageInList(image));
2133 }
2134 #endif
2135 \f
2136 /*
2137 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2138 %                                                                             %
2139 %                                                                             %
2140 %                                                                             %
2141 %   R e g i s t e r T I F F I m a g e                                         %
2142 %                                                                             %
2143 %                                                                             %
2144 %                                                                             %
2145 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2146 %
2147 %  RegisterTIFFImage() adds properties for the TIFF image format to
2148 %  the list of supported formats.  The properties include the image format
2149 %  tag, a method to read and/or write the format, whether the format
2150 %  supports the saving of more than one frame to the same file or blob,
2151 %  whether the format supports native in-memory I/O, and a brief
2152 %  description of the format.
2153 %
2154 %  The format of the RegisterTIFFImage method is:
2155 %
2156 %      size_t RegisterTIFFImage(void)
2157 %
2158 */
2159
2160 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2161 static TIFFExtendProc
2162   tag_extender = (TIFFExtendProc) NULL;
2163
2164 static void TIFFIgnoreTags(TIFF *tiff)
2165 {
2166   char
2167     *q;
2168
2169   const char
2170     *p,
2171     *tags;
2172
2173   Image
2174    *image;
2175
2176   register ssize_t
2177     i;
2178
2179   size_t
2180     count;
2181
2182   TIFFFieldInfo
2183     *ignore;
2184
2185   if (TIFFGetReadProc(tiff) != TIFFReadBlob)
2186     return;
2187   image=(Image *)TIFFClientdata(tiff);
2188   tags=GetImageArtifact(image,"tiff:ignore-tags");
2189   if (tags == (const char *) NULL)
2190     return;
2191   count=0;
2192   p=tags;
2193   while (*p != '\0')
2194   {
2195     while ((isspace((int) ((unsigned char) *p)) != 0))
2196       p++;
2197
2198     (void) strtol(p,&q,10);
2199     if (p == q)
2200       return;
2201
2202     p=q;
2203     count++;
2204
2205     while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
2206       p++;
2207   }
2208   if (count == 0)
2209     return;
2210   i=0;
2211   p=tags;
2212   ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
2213   /* This also sets field_bit to 0 (FIELD_IGNORE) */
2214   ResetMagickMemory(ignore,0,count*sizeof(*ignore));
2215   while (*p != '\0')
2216   {
2217     while ((isspace((int) ((unsigned char) *p)) != 0))
2218       p++;
2219
2220     ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
2221
2222     p=q;
2223     i++;
2224
2225     while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
2226       p++;
2227   }
2228   (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
2229   ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
2230 }
2231
2232 static void TIFFTagExtender(TIFF *tiff)
2233 {
2234   static const TIFFFieldInfo
2235     TIFFExtensions[] =
2236     {
2237       { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
2238         (char *) "PhotoshopLayerData" },
2239       { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
2240         (char *) "Microscope" }
2241     };
2242
2243   TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
2244     sizeof(*TIFFExtensions));
2245   if (tag_extender != (TIFFExtendProc) NULL)
2246     (*tag_extender)(tiff);
2247   TIFFIgnoreTags(tiff);
2248 }
2249 #endif
2250
2251 ModuleExport size_t RegisterTIFFImage(void)
2252 {
2253 #define TIFFDescription  "Tagged Image File Format"
2254
2255   char
2256     version[MagickPathExtent];
2257
2258   MagickInfo
2259     *entry;
2260
2261   if (tiff_semaphore == (SemaphoreInfo *) NULL)
2262     ActivateSemaphoreInfo(&tiff_semaphore);
2263   LockSemaphoreInfo(tiff_semaphore);
2264   if (instantiate_key == MagickFalse)
2265     {
2266       if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
2267         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2268       error_handler=TIFFSetErrorHandler(TIFFErrors);
2269       warning_handler=TIFFSetWarningHandler(TIFFWarnings);
2270 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2271       if (tag_extender == (TIFFExtendProc) NULL)
2272         tag_extender=TIFFSetTagExtender(TIFFTagExtender);
2273 #endif
2274       instantiate_key=MagickTrue;
2275     }
2276   UnlockSemaphoreInfo(tiff_semaphore);
2277   *version='\0';
2278 #if defined(TIFF_VERSION)
2279   (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION);
2280 #endif
2281 #if defined(MAGICKCORE_TIFF_DELEGATE)
2282   {
2283     const char
2284       *p;
2285
2286     register ssize_t
2287       i;
2288
2289     p=TIFFGetVersion();
2290     for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++)
2291       version[i]=(*p++);
2292     version[i]='\0';
2293   }
2294 #endif
2295
2296   entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4");
2297 #if defined(MAGICKCORE_TIFF_DELEGATE)
2298   entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
2299   entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
2300 #endif
2301   entry->flags|=CoderRawSupportFlag;
2302   entry->flags|=CoderEndianSupportFlag;
2303   entry->flags|=CoderSeekableStreamFlag;
2304   entry->flags^=CoderAdjoinFlag;
2305   entry->flags^=CoderUseExtensionFlag;
2306   entry->format_type=ImplicitFormatType;
2307   entry->mime_type=ConstantString("image/tiff");
2308   (void) RegisterMagickInfo(entry);
2309   entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF");
2310 #if defined(MAGICKCORE_TIFF_DELEGATE)
2311   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2312   entry->encoder=(EncodeImageHandler *) WritePTIFImage;
2313 #endif
2314   entry->flags|=CoderEndianSupportFlag;
2315   entry->flags|=CoderSeekableStreamFlag;
2316   entry->flags^=CoderUseExtensionFlag;
2317   entry->mime_type=ConstantString("image/tiff");
2318   (void) RegisterMagickInfo(entry);
2319   entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription);
2320 #if defined(MAGICKCORE_TIFF_DELEGATE)
2321   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2322   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2323 #endif
2324   entry->flags|=CoderEndianSupportFlag;
2325   entry->flags|=CoderSeekableStreamFlag;
2326   entry->flags|=CoderStealthFlag;
2327   entry->flags^=CoderUseExtensionFlag;
2328   if (*version != '\0')
2329     entry->version=ConstantString(version);
2330   entry->mime_type=ConstantString("image/tiff");
2331   (void) RegisterMagickInfo(entry);
2332   entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription);
2333 #if defined(MAGICKCORE_TIFF_DELEGATE)
2334   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2335   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2336 #endif
2337   entry->magick=(IsImageFormatHandler *) IsTIFF;
2338   entry->flags|=CoderEndianSupportFlag;
2339   entry->flags|=CoderSeekableStreamFlag;
2340   entry->flags^=CoderUseExtensionFlag;
2341   if (*version != '\0')
2342     entry->version=ConstantString(version);
2343   entry->mime_type=ConstantString("image/tiff");
2344   (void) RegisterMagickInfo(entry);
2345   entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)");
2346 #if defined(TIFF_VERSION_BIG)
2347   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2348   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2349 #endif
2350   entry->flags|=CoderEndianSupportFlag;
2351   entry->flags|=CoderSeekableStreamFlag;
2352   entry->flags^=CoderAdjoinFlag;
2353   entry->flags^=CoderUseExtensionFlag;
2354   if (*version != '\0')
2355     entry->version=ConstantString(version);
2356   entry->mime_type=ConstantString("image/tiff");
2357   (void) RegisterMagickInfo(entry);
2358   return(MagickImageCoderSignature);
2359 }
2360 \f
2361 /*
2362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2363 %                                                                             %
2364 %                                                                             %
2365 %                                                                             %
2366 %   U n r e g i s t e r T I F F I m a g e                                     %
2367 %                                                                             %
2368 %                                                                             %
2369 %                                                                             %
2370 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2371 %
2372 %  UnregisterTIFFImage() removes format registrations made by the TIFF module
2373 %  from the list of supported formats.
2374 %
2375 %  The format of the UnregisterTIFFImage method is:
2376 %
2377 %      UnregisterTIFFImage(void)
2378 %
2379 */
2380 ModuleExport void UnregisterTIFFImage(void)
2381 {
2382   (void) UnregisterMagickInfo("TIFF64");
2383   (void) UnregisterMagickInfo("TIFF");
2384   (void) UnregisterMagickInfo("TIF");
2385   (void) UnregisterMagickInfo("PTIF");
2386   if (tiff_semaphore == (SemaphoreInfo *) NULL)
2387     ActivateSemaphoreInfo(&tiff_semaphore);
2388   LockSemaphoreInfo(tiff_semaphore);
2389   if (instantiate_key != MagickFalse)
2390     {
2391 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2392       if (tag_extender == (TIFFExtendProc) NULL)
2393         (void) TIFFSetTagExtender(tag_extender);
2394 #endif
2395       if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
2396         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2397       (void) TIFFSetWarningHandler(warning_handler);
2398       (void) TIFFSetErrorHandler(error_handler);
2399       instantiate_key=MagickFalse;
2400     }
2401   UnlockSemaphoreInfo(tiff_semaphore);
2402   RelinquishSemaphoreInfo(&tiff_semaphore);
2403 }
2404 \f
2405 #if defined(MAGICKCORE_TIFF_DELEGATE)
2406 /*
2407 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2408 %                                                                             %
2409 %                                                                             %
2410 %                                                                             %
2411 %   W r i t e G R O U P 4 I m a g e                                           %
2412 %                                                                             %
2413 %                                                                             %
2414 %                                                                             %
2415 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2416 %
2417 %  WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
2418 %
2419 %  The format of the WriteGROUP4Image method is:
2420 %
2421 %      MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2422 %        Image *image,ExceptionInfo *)
2423 %
2424 %  A description of each parameter follows:
2425 %
2426 %    o image_info: the image info.
2427 %
2428 %    o image:  The image.
2429 %
2430 %    o exception: return any errors or warnings in this structure.
2431 %
2432 */
2433 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2434   Image *image,ExceptionInfo *exception)
2435 {
2436   char
2437     filename[MagickPathExtent];
2438
2439   FILE
2440     *file;
2441
2442   Image
2443     *huffman_image;
2444
2445   ImageInfo
2446     *write_info;
2447
2448   int
2449     unique_file;
2450
2451   MagickBooleanType
2452     status;
2453
2454   register ssize_t
2455     i;
2456
2457   ssize_t
2458     count;
2459
2460   TIFF
2461     *tiff;
2462
2463   toff_t
2464     *byte_count,
2465     strip_size;
2466
2467   unsigned char
2468     *buffer;
2469
2470   /*
2471     Write image as CCITT Group4 TIFF image to a temporary file.
2472   */
2473   assert(image_info != (const ImageInfo *) NULL);
2474   assert(image_info->signature == MagickCoreSignature);
2475   assert(image != (Image *) NULL);
2476   assert(image->signature == MagickCoreSignature);
2477   if (image->debug != MagickFalse)
2478     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2479   assert(exception != (ExceptionInfo *) NULL);
2480   assert(exception->signature == MagickCoreSignature);
2481   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2482   if (status == MagickFalse)
2483     return(status);
2484   huffman_image=CloneImage(image,0,0,MagickTrue,exception);
2485   if (huffman_image == (Image *) NULL)
2486     {
2487       (void) CloseBlob(image);
2488       return(MagickFalse);
2489     }
2490   huffman_image->endian=MSBEndian;
2491   file=(FILE *) NULL;
2492   unique_file=AcquireUniqueFileResource(filename);
2493   if (unique_file != -1)
2494     file=fdopen(unique_file,"wb");
2495   if ((unique_file == -1) || (file == (FILE *) NULL))
2496     {
2497       ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
2498         filename);
2499       return(MagickFalse);
2500     }
2501   (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s",
2502     filename);
2503   (void) SetImageType(huffman_image,BilevelType,exception);
2504   write_info=CloneImageInfo((ImageInfo *) NULL);
2505   SetImageInfoFile(write_info,file);
2506   (void) SetImageDepth(image,1,exception);
2507   (void) SetImageType(image,BilevelType,exception);
2508   write_info->compression=Group4Compression;
2509   write_info->type=BilevelType;
2510   (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
2511   status=WriteTIFFImage(write_info,huffman_image,exception);
2512   (void) fflush(file);
2513   write_info=DestroyImageInfo(write_info);
2514   if (status == MagickFalse)
2515     {
2516       huffman_image=DestroyImage(huffman_image);
2517       (void) fclose(file);
2518       (void) RelinquishUniqueFileResource(filename);
2519       return(MagickFalse);
2520     }
2521   tiff=TIFFOpen(filename,"rb");
2522   if (tiff == (TIFF *) NULL)
2523     {
2524       huffman_image=DestroyImage(huffman_image);
2525       (void) fclose(file);
2526       (void) RelinquishUniqueFileResource(filename);
2527       ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
2528         image_info->filename);
2529       return(MagickFalse);
2530     }
2531   /*
2532     Allocate raw strip buffer.
2533   */
2534   if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2535     {
2536       TIFFClose(tiff);
2537       huffman_image=DestroyImage(huffman_image);
2538       (void) fclose(file);
2539       (void) RelinquishUniqueFileResource(filename);
2540       return(MagickFalse);
2541     }
2542   strip_size=byte_count[0];
2543   for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2544     if (byte_count[i] > strip_size)
2545       strip_size=byte_count[i];
2546   buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2547     sizeof(*buffer));
2548   if (buffer == (unsigned char *) NULL)
2549     {
2550       TIFFClose(tiff);
2551       huffman_image=DestroyImage(huffman_image);
2552       (void) fclose(file);
2553       (void) RelinquishUniqueFileResource(filename);
2554       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2555         image_info->filename);
2556     }
2557   /*
2558     Compress runlength encoded to 2D Huffman pixels.
2559   */
2560   for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2561   {
2562     count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2563     if (WriteBlob(image,(size_t) count,buffer) != count)
2564       status=MagickFalse;
2565   }
2566   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2567   TIFFClose(tiff);
2568   huffman_image=DestroyImage(huffman_image);
2569   (void) fclose(file);
2570   (void) RelinquishUniqueFileResource(filename);
2571   (void) CloseBlob(image);
2572   return(status);
2573 }
2574 #endif
2575 \f
2576 #if defined(MAGICKCORE_TIFF_DELEGATE)
2577 /*
2578 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2579 %                                                                             %
2580 %                                                                             %
2581 %                                                                             %
2582 %   W r i t e P T I F I m a g e                                               %
2583 %                                                                             %
2584 %                                                                             %
2585 %                                                                             %
2586 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2587 %
2588 %  WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2589 %  format.
2590 %
2591 %  The format of the WritePTIFImage method is:
2592 %
2593 %      MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2594 %        Image *image,ExceptionInfo *exception)
2595 %
2596 %  A description of each parameter follows:
2597 %
2598 %    o image_info: the image info.
2599 %
2600 %    o image:  The image.
2601 %
2602 %    o exception: return any errors or warnings in this structure.
2603 %
2604 */
2605 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2606   Image *image,ExceptionInfo *exception)
2607 {
2608   Image
2609     *images,
2610     *next,
2611     *pyramid_image;
2612
2613   ImageInfo
2614     *write_info;
2615
2616   MagickBooleanType
2617     status;
2618
2619   PointInfo
2620     resolution;
2621
2622   size_t
2623     columns,
2624     rows;
2625
2626   /*
2627     Create pyramid-encoded TIFF image.
2628   */
2629   images=NewImageList();
2630   for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2631   {
2632     Image
2633       *clone_image;
2634
2635     clone_image=CloneImage(next,0,0,MagickFalse,exception);
2636     if (clone_image == (Image *) NULL)
2637       break;
2638     clone_image->previous=NewImageList();
2639     clone_image->next=NewImageList();
2640     (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
2641     AppendImageToList(&images,clone_image);
2642     columns=next->columns;
2643     rows=next->rows;
2644     resolution=next->resolution;
2645     while ((columns > 64) && (rows > 64))
2646     {
2647       columns/=2;
2648       rows/=2;
2649       resolution.x/=2;
2650       resolution.y/=2;
2651       pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
2652       if (pyramid_image == (Image *) NULL)
2653         break;
2654       pyramid_image->resolution=resolution;
2655       (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
2656         exception);
2657       AppendImageToList(&images,pyramid_image);
2658     }
2659   }
2660   images=GetFirstImageInList(images);
2661   /*
2662     Write pyramid-encoded TIFF image.
2663   */
2664   write_info=CloneImageInfo(image_info);
2665   write_info->adjoin=MagickTrue;
2666   (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
2667   (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
2668   status=WriteTIFFImage(write_info,images,exception);
2669   images=DestroyImageList(images);
2670   write_info=DestroyImageInfo(write_info);
2671   return(status);
2672 }
2673 #endif
2674 \f
2675 #if defined(MAGICKCORE_TIFF_DELEGATE)
2676 /*
2677 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2678 %                                                                             %
2679 %                                                                             %
2680 %   W r i t e T I F F I m a g e                                               %
2681 %                                                                             %
2682 %                                                                             %
2683 %                                                                             %
2684 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2685 %
2686 %  WriteTIFFImage() writes an image in the Tagged image file format.
2687 %
2688 %  The format of the WriteTIFFImage method is:
2689 %
2690 %      MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2691 %        Image *image,ExceptionInfo *exception)
2692 %
2693 %  A description of each parameter follows:
2694 %
2695 %    o image_info: the image info.
2696 %
2697 %    o image:  The image.
2698 %
2699 %    o exception: return any errors or warnings in this structure.
2700 %
2701 */
2702
2703 typedef struct _TIFFInfo
2704 {
2705   RectangleInfo
2706     tile_geometry;
2707
2708   unsigned char
2709     *scanline,
2710     *scanlines,
2711     *pixels;
2712 } TIFFInfo;
2713
2714 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2715 {
2716   assert(tiff_info != (TIFFInfo *) NULL);
2717   if (tiff_info->scanlines != (unsigned char *) NULL)
2718     tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2719       tiff_info->scanlines);
2720   if (tiff_info->pixels != (unsigned char *) NULL)
2721     tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2722       tiff_info->pixels);
2723 }
2724
2725 static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
2726 {
2727   CacheView
2728     *image_view;
2729
2730   MagickBooleanType
2731     status;
2732
2733   ssize_t
2734     y;
2735
2736   status=MagickTrue;
2737   image_view=AcquireAuthenticCacheView(image,exception);
2738   for (y=0; y < (ssize_t) image->rows; y++)
2739   {
2740     register Quantum
2741       *magick_restrict q;
2742
2743     register ssize_t
2744       x;
2745
2746     if (status == MagickFalse)
2747       continue;
2748     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2749     if (q == (Quantum *) NULL)
2750       {
2751         status=MagickFalse;
2752         continue;
2753       }
2754     for (x=0; x < (ssize_t) image->columns; x++)
2755     {
2756       double
2757         a,
2758         b;
2759
2760       a=QuantumScale*GetPixela(image,q)-0.5;
2761       if (a < 0.0)
2762         a+=1.0;
2763       b=QuantumScale*GetPixelb(image,q)-0.5;
2764       if (b < 0.0)
2765         b+=1.0;
2766       SetPixela(image,QuantumRange*a,q);
2767       SetPixelb(image,QuantumRange*b,q);
2768       q+=GetPixelChannels(image);
2769     }
2770     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2771       status=MagickFalse;
2772   }
2773   image_view=DestroyCacheView(image_view);
2774   return(status);
2775 }
2776
2777 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
2778   TIFF *tiff,TIFFInfo *tiff_info)
2779 {
2780   const char
2781     *option;
2782
2783   MagickStatusType
2784     flags;
2785
2786   uint32
2787     tile_columns,
2788     tile_rows;
2789
2790   assert(tiff_info != (TIFFInfo *) NULL);
2791   (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2792   option=GetImageOption(image_info,"tiff:tile-geometry");
2793   if (option == (const char *) NULL)
2794     {
2795       uint32
2796         rows_per_strip;
2797
2798       option=GetImageOption(image_info,"tiff:rows-per-strip");
2799       if (option != (const char *) NULL)
2800         rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
2801       else
2802         if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0)
2803           rows_per_strip=0;  /* use default */
2804       rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip);
2805       (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
2806       return(MagickTrue);
2807     }
2808   /*
2809     Create tiled TIFF, ignore "tiff:rows-per-strip".
2810   */
2811   flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2812   if ((flags & HeightValue) == 0)
2813     tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2814   tile_columns=(uint32) tiff_info->tile_geometry.width;
2815   tile_rows=(uint32) tiff_info->tile_geometry.height;
2816   TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2817   (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2818   (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2819   tiff_info->tile_geometry.width=tile_columns;
2820   tiff_info->tile_geometry.height=tile_rows;
2821   tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2822     tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2823   tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2824     tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2825   if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2826       (tiff_info->pixels == (unsigned char *) NULL))
2827     {
2828       DestroyTIFFInfo(tiff_info);
2829       return(MagickFalse);
2830     }
2831   return(MagickTrue);
2832 }
2833
2834 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2835   tsample_t sample,Image *image)
2836 {
2837   int32
2838     status;
2839
2840   register ssize_t
2841     i;
2842
2843   register unsigned char
2844     *p,
2845     *q;
2846
2847   size_t
2848     number_tiles,
2849     tile_width;
2850
2851   ssize_t
2852     bytes_per_pixel,
2853     j,
2854     k,
2855     l;
2856
2857   if (TIFFIsTiled(tiff) == 0)
2858     return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2859   /*
2860     Fill scanlines to tile height.
2861   */
2862   i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2863   (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2864     (size_t) TIFFScanlineSize(tiff));
2865   if (((size_t) (row % tiff_info->tile_geometry.height) !=
2866       (tiff_info->tile_geometry.height-1)) &&
2867       (row != (ssize_t) (image->rows-1)))
2868     return(0);
2869   /*
2870     Write tile to TIFF image.
2871   */
2872   status=0;
2873   bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
2874     tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
2875   number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2876     tiff_info->tile_geometry.width;
2877   for (i=0; i < (ssize_t) number_tiles; i++)
2878   {
2879     tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2880       tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2881     for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2882       for (k=0; k < (ssize_t) tile_width; k++)
2883       {
2884         if (bytes_per_pixel == 0)
2885           {
2886             p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2887               tiff_info->tile_geometry.width+k)/8);
2888             q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2889             *q++=(*p++);
2890             continue;
2891           }
2892         p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2893           tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2894         q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2895         for (l=0; l < bytes_per_pixel; l++)
2896           *q++=(*p++);
2897       }
2898     if ((i*tiff_info->tile_geometry.width) != image->columns)
2899       status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2900         tiff_info->tile_geometry.width),(uint32) ((row/
2901         tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2902         sample);
2903     if (status < 0)
2904       break;
2905   }
2906   return(status);
2907 }
2908
2909 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2910 {
2911   const char
2912     *name;
2913
2914   const StringInfo
2915     *profile;
2916
2917   if (image->profiles == (void *) NULL)
2918     return;
2919   ResetImageProfileIterator(image);
2920   for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2921   {
2922     profile=GetImageProfile(image,name);
2923     if (GetStringInfoLength(profile) == 0)
2924       {
2925         name=GetNextImageProfile(image);
2926         continue;
2927       }
2928 #if defined(TIFFTAG_XMLPACKET)
2929     if (LocaleCompare(name,"xmp") == 0)
2930       (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2931         profile),GetStringInfoDatum(profile));
2932 #endif
2933 #if defined(TIFFTAG_ICCPROFILE)
2934     if (LocaleCompare(name,"icc") == 0)
2935       (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2936         profile),GetStringInfoDatum(profile));
2937 #endif
2938     if (LocaleCompare(name,"iptc") == 0)
2939       {
2940         size_t
2941           length;
2942
2943         StringInfo
2944           *iptc_profile;
2945
2946         iptc_profile=CloneStringInfo(profile);
2947         length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2948           0x03);
2949         SetStringInfoLength(iptc_profile,length);
2950         if (TIFFIsByteSwapped(tiff))
2951           TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2952             (unsigned long) (length/4));
2953         (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2954           GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2955         iptc_profile=DestroyStringInfo(iptc_profile);
2956       }
2957 #if defined(TIFFTAG_PHOTOSHOP)
2958     if (LocaleCompare(name,"8bim") == 0)
2959       (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2960         GetStringInfoLength(profile),GetStringInfoDatum(profile));
2961 #endif
2962     if (LocaleCompare(name,"tiff:37724") == 0)
2963       (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
2964         GetStringInfoDatum(profile));
2965     if (LocaleCompare(name,"tiff:34118") == 0)
2966       (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
2967         GetStringInfoDatum(profile));
2968     name=GetNextImageProfile(image);
2969   }
2970 }
2971
2972 static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
2973   Image *image,ExceptionInfo *exception)
2974 {
2975   const char
2976     *value;
2977
2978   value=GetImageArtifact(image,"tiff:document");
2979   if (value != (const char *) NULL)
2980     (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
2981   value=GetImageArtifact(image,"tiff:hostcomputer");
2982   if (value != (const char *) NULL)
2983     (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2984   value=GetImageArtifact(image,"tiff:artist");
2985   if (value != (const char *) NULL)
2986     (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2987   value=GetImageArtifact(image,"tiff:timestamp");
2988   if (value != (const char *) NULL)
2989     (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2990   value=GetImageArtifact(image,"tiff:make");
2991   if (value != (const char *) NULL)
2992     (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2993   value=GetImageArtifact(image,"tiff:model");
2994   if (value != (const char *) NULL)
2995     (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2996   value=GetImageArtifact(image,"tiff:software");
2997   if (value != (const char *) NULL)
2998     (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2999   value=GetImageArtifact(image,"tiff:copyright");
3000   if (value != (const char *) NULL)
3001     (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
3002   value=GetImageArtifact(image,"kodak-33423");
3003   if (value != (const char *) NULL)
3004     (void) TIFFSetField(tiff,33423,value);
3005   value=GetImageArtifact(image,"kodak-36867");
3006   if (value != (const char *) NULL)
3007     (void) TIFFSetField(tiff,36867,value);
3008   value=GetImageProperty(image,"label",exception);
3009   if (value != (const char *) NULL)
3010     (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
3011   value=GetImageProperty(image,"comment",exception);
3012   if (value != (const char *) NULL)
3013     (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
3014   value=GetImageArtifact(image,"tiff:subfiletype");
3015   if (value != (const char *) NULL)
3016     {
3017       if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
3018         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
3019       else
3020         if (LocaleCompare(value,"PAGE") == 0)
3021           (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3022         else
3023           if (LocaleCompare(value,"MASK") == 0)
3024             (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
3025     }
3026   else
3027     {
3028       uint16
3029         page,
3030         pages;
3031
3032       page=(uint16) image->scene;
3033       pages=(uint16) GetImageListLength(image);
3034       if ((image_info->adjoin != MagickFalse) && (pages > 1))
3035         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3036       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3037     }
3038 }
3039
3040 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
3041   ExceptionInfo *exception)
3042 {
3043 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
3044   const char
3045     *value;
3046
3047   register ssize_t
3048     i;
3049
3050   uint32
3051     offset;
3052
3053   /*
3054     Write EXIF properties.
3055   */
3056   offset=0;
3057   (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
3058   for (i=0; exif_info[i].tag != 0; i++)
3059   {
3060     value=GetImageProperty(image,exif_info[i].property,exception);
3061     if (value == (const char *) NULL)
3062       continue;
3063     switch (exif_info[i].type)
3064     {
3065       case TIFF_ASCII:
3066       {
3067         (void) TIFFSetField(tiff,exif_info[i].tag,value);
3068         break;
3069       }
3070       case TIFF_SHORT:
3071       {
3072         uint16
3073           field;
3074
3075         field=(uint16) StringToLong(value);
3076         (void) TIFFSetField(tiff,exif_info[i].tag,field);
3077         break;
3078       }
3079       case TIFF_LONG:
3080       {
3081         uint16
3082           field;
3083
3084         field=(uint16) StringToLong(value);
3085         (void) TIFFSetField(tiff,exif_info[i].tag,field);
3086         break;
3087       }
3088       case TIFF_RATIONAL:
3089       case TIFF_SRATIONAL:
3090       {
3091         float
3092           field;
3093
3094         field=StringToDouble(value,(char **) NULL);
3095         (void) TIFFSetField(tiff,exif_info[i].tag,field);
3096         break;
3097       }
3098       default:
3099         break;
3100     }
3101   }
3102   /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
3103 #else
3104   (void) tiff;
3105   (void) image;
3106 #endif
3107 }
3108
3109 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
3110   Image *image,ExceptionInfo *exception)
3111 {
3112   const char
3113     *mode,
3114     *option;
3115
3116   CompressionType
3117     compression;
3118
3119   EndianType
3120     endian_type;
3121
3122   MagickBooleanType
3123     debug,
3124     status;
3125
3126   MagickOffsetType
3127     scene;
3128
3129   QuantumInfo
3130     *quantum_info;
3131
3132   QuantumType
3133     quantum_type;
3134
3135   register ssize_t
3136     i;
3137
3138   size_t
3139     length;
3140
3141   ssize_t
3142     y;
3143
3144   TIFF
3145     *tiff;
3146
3147   TIFFInfo
3148     tiff_info;
3149
3150   uint16
3151     bits_per_sample,
3152     compress_tag,
3153     endian,
3154     photometric;
3155
3156   unsigned char
3157     *pixels;
3158
3159   /*
3160     Open TIFF file.
3161   */
3162   assert(image_info != (const ImageInfo *) NULL);
3163   assert(image_info->signature == MagickCoreSignature);
3164   assert(image != (Image *) NULL);
3165   assert(image->signature == MagickCoreSignature);
3166   if (image->debug != MagickFalse)
3167     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3168   assert(exception != (ExceptionInfo *) NULL);
3169   assert(exception->signature == MagickCoreSignature);
3170   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
3171   if (status == MagickFalse)
3172     return(status);
3173   (void) SetMagickThreadValue(tiff_exception,exception);
3174   endian_type=UndefinedEndian;
3175   option=GetImageOption(image_info,"tiff:endian");
3176   if (option != (const char *) NULL)
3177     {
3178       if (LocaleNCompare(option,"msb",3) == 0)
3179         endian_type=MSBEndian;
3180       if (LocaleNCompare(option,"lsb",3) == 0)
3181         endian_type=LSBEndian;;
3182     }
3183   switch (endian_type)
3184   {
3185     case LSBEndian: mode="wl"; break;
3186     case MSBEndian: mode="wb"; break;
3187     default: mode="w"; break;
3188   }
3189 #if defined(TIFF_VERSION_BIG)
3190   if (LocaleCompare(image_info->magick,"TIFF64") == 0)
3191     switch (endian_type)
3192     {
3193       case LSBEndian: mode="wl8"; break;
3194       case MSBEndian: mode="wb8"; break;
3195       default: mode="w8"; break;
3196     }
3197 #endif
3198   tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
3199     TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
3200     TIFFUnmapBlob);
3201   if (tiff == (TIFF *) NULL)
3202     return(MagickFalse);
3203   scene=0;
3204   debug=IsEventLogging();
3205   (void) debug;
3206   do
3207   {
3208     /*
3209       Initialize TIFF fields.
3210     */
3211     if ((image_info->type != UndefinedType) &&
3212         (image_info->type != OptimizeType))
3213       (void) SetImageType(image,image_info->type,exception);
3214     compression=UndefinedCompression;
3215     if (image->compression != JPEGCompression)
3216       compression=image->compression;
3217     if (image_info->compression != UndefinedCompression)
3218       compression=image_info->compression;
3219     switch (compression)
3220     {
3221       case FaxCompression:
3222       case Group4Compression:
3223       {
3224         (void) SetImageType(image,BilevelType,exception);
3225         (void) SetImageDepth(image,1,exception);
3226         break;
3227       }
3228       case JPEGCompression:
3229       {
3230         (void) SetImageStorageClass(image,DirectClass,exception);
3231         (void) SetImageDepth(image,8,exception);
3232         break;
3233       }
3234       default:
3235         break;
3236     }
3237     quantum_info=AcquireQuantumInfo(image_info,image);
3238     if (quantum_info == (QuantumInfo *) NULL)
3239       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3240     if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
3241         (quantum_info->format == UndefinedQuantumFormat) &&
3242         (IsHighDynamicRangeImage(image,exception) != MagickFalse))
3243       {
3244         status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
3245         if (status == MagickFalse)
3246           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3247       }
3248     if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
3249         (GetPreviousImageInList(image) != (Image *) NULL))
3250       (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
3251     if ((image->columns != (uint32) image->columns) ||
3252         (image->rows != (uint32) image->rows))
3253       ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
3254     (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
3255     (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
3256     switch (compression)
3257     {
3258       case FaxCompression:
3259       {
3260         compress_tag=COMPRESSION_CCITTFAX3;
3261         SetQuantumMinIsWhite(quantum_info,MagickTrue);
3262         break;
3263       }
3264       case Group4Compression:
3265       {
3266         compress_tag=COMPRESSION_CCITTFAX4;
3267         SetQuantumMinIsWhite(quantum_info,MagickTrue);
3268         break;
3269       }
3270 #if defined(COMPRESSION_JBIG)
3271       case JBIG1Compression:
3272       {
3273         compress_tag=COMPRESSION_JBIG;
3274         break;
3275       }
3276 #endif
3277       case JPEGCompression:
3278       {
3279         compress_tag=COMPRESSION_JPEG;
3280         break;
3281       }
3282 #if defined(COMPRESSION_LZMA)
3283       case LZMACompression:
3284       {
3285         compress_tag=COMPRESSION_LZMA;
3286         break;
3287       }
3288 #endif
3289       case LZWCompression:
3290       {
3291         compress_tag=COMPRESSION_LZW;
3292         break;
3293       }
3294       case RLECompression:
3295       {
3296         compress_tag=COMPRESSION_PACKBITS;
3297         break;
3298       }
3299       case ZipCompression:
3300       {
3301         compress_tag=COMPRESSION_ADOBE_DEFLATE;
3302         break;
3303       }
3304       case NoCompression:
3305       default:
3306       {
3307         compress_tag=COMPRESSION_NONE;
3308         break;
3309       }
3310     }
3311 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
3312     if ((compress_tag != COMPRESSION_NONE) &&
3313         (TIFFIsCODECConfigured(compress_tag) == 0))
3314       {
3315         (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3316           "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
3317           MagickCompressOptions,(ssize_t) compression));
3318         compress_tag=COMPRESSION_NONE;
3319         compression=NoCompression;
3320       }
3321 #else
3322       switch (compress_tag)
3323       {
3324 #if defined(CCITT_SUPPORT)
3325         case COMPRESSION_CCITTFAX3:
3326         case COMPRESSION_CCITTFAX4:
3327 #endif
3328 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
3329         case COMPRESSION_JPEG:
3330 #endif
3331 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3332         case COMPRESSION_LZMA:
3333 #endif
3334 #if defined(LZW_SUPPORT)
3335         case COMPRESSION_LZW:
3336 #endif
3337 #if defined(PACKBITS_SUPPORT)
3338         case COMPRESSION_PACKBITS:
3339 #endif
3340 #if defined(ZIP_SUPPORT)
3341         case COMPRESSION_ADOBE_DEFLATE:
3342 #endif
3343         case COMPRESSION_NONE:
3344           break;
3345         default:
3346         {
3347           (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3348             "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
3349               MagickCompressOptions,(ssize_t) compression));
3350           compress_tag=COMPRESSION_NONE;
3351           compression=NoCompression;
3352           break;
3353         }
3354       }
3355 #endif
3356     if (image->colorspace == CMYKColorspace)
3357       {
3358         photometric=PHOTOMETRIC_SEPARATED;
3359         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
3360         (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
3361       }
3362     else
3363       {
3364         /*
3365           Full color TIFF raster.
3366         */
3367         if (image->colorspace == LabColorspace)
3368           {
3369             photometric=PHOTOMETRIC_CIELAB;
3370             EncodeLabImage(image,exception);
3371           }
3372         else
3373           if (image->colorspace == YCbCrColorspace)
3374             {
3375               photometric=PHOTOMETRIC_YCBCR;
3376               (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
3377               (void) SetImageStorageClass(image,DirectClass,exception);
3378               (void) SetImageDepth(image,8,exception);
3379             }
3380           else
3381             photometric=PHOTOMETRIC_RGB;
3382         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
3383         if ((image_info->type != TrueColorType) &&
3384             (image_info->type != TrueColorAlphaType))
3385           {
3386             if ((image_info->type != PaletteType) &&
3387                 (SetImageGray(image,exception) != MagickFalse))
3388               {
3389                 photometric=(uint16) (quantum_info->min_is_white !=
3390                   MagickFalse ? PHOTOMETRIC_MINISWHITE :
3391                   PHOTOMETRIC_MINISBLACK);
3392                 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3393                 if ((image->depth == 1) &&
3394                     (image->alpha_trait == UndefinedPixelTrait))
3395                   SetImageMonochrome(image,exception);
3396               }
3397             else
3398               if (image->storage_class == PseudoClass)
3399                 {
3400                   size_t
3401                     depth;
3402
3403                   /*
3404                     Colormapped TIFF raster.
3405                   */
3406                   (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3407                   photometric=PHOTOMETRIC_PALETTE;
3408                   depth=1;
3409                   while ((GetQuantumRange(depth)+1) < image->colors)
3410                     depth<<=1;
3411                   status=SetQuantumDepth(image,quantum_info,depth);
3412                   if (status == MagickFalse)
3413                     ThrowWriterException(ResourceLimitError,
3414                       "MemoryAllocationFailed");
3415                 }
3416           }
3417       }
3418     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
3419     if ((compress_tag == COMPRESSION_CCITTFAX3) &&
3420         (photometric != PHOTOMETRIC_MINISWHITE))
3421       {
3422         compress_tag=COMPRESSION_NONE;
3423         endian=FILLORDER_MSB2LSB;
3424       }
3425     else
3426       if ((compress_tag == COMPRESSION_CCITTFAX4) &&
3427          (photometric != PHOTOMETRIC_MINISWHITE))
3428        {
3429          compress_tag=COMPRESSION_NONE;
3430          endian=FILLORDER_MSB2LSB;
3431        }
3432     option=GetImageOption(image_info,"tiff:fill-order");
3433     if (option != (const char *) NULL)
3434       {
3435         if (LocaleNCompare(option,"msb",3) == 0)
3436           endian=FILLORDER_MSB2LSB;
3437         if (LocaleNCompare(option,"lsb",3) == 0)
3438           endian=FILLORDER_LSB2MSB;
3439       }
3440     (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
3441     (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
3442     (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
3443     if (image->alpha_trait != UndefinedPixelTrait)
3444       {
3445         uint16
3446           extra_samples,
3447           sample_info[1],
3448           samples_per_pixel;
3449
3450         /*
3451           TIFF has a matte channel.
3452         */
3453         extra_samples=1;
3454         sample_info[0]=EXTRASAMPLE_UNASSALPHA;
3455         option=GetImageOption(image_info,"tiff:alpha");
3456         if (option != (const char *) NULL)
3457           {
3458             if (LocaleCompare(option,"associated") == 0)
3459               sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
3460             else
3461               if (LocaleCompare(option,"unspecified") == 0)
3462                 sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
3463           }
3464         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
3465           &samples_per_pixel);
3466         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
3467         (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
3468           &sample_info);
3469         if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
3470           SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
3471       }
3472     (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
3473     switch (quantum_info->format)
3474     {
3475       case FloatingPointQuantumFormat:
3476       {
3477         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
3478         (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
3479         (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
3480         break;
3481       }
3482       case SignedQuantumFormat:
3483       {
3484         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
3485         break;
3486       }
3487       case UnsignedQuantumFormat:
3488       {
3489         (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
3490         break;
3491       }
3492       default:
3493         break;
3494     }
3495     (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
3496     (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3497     if (photometric == PHOTOMETRIC_RGB)
3498       if ((image_info->interlace == PlaneInterlace) ||
3499           (image_info->interlace == PartitionInterlace))
3500         (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
3501     switch (compress_tag)
3502     {
3503       case COMPRESSION_JPEG:
3504       {
3505 #if defined(JPEG_SUPPORT)
3506
3507
3508         if (image_info->quality != UndefinedCompressionQuality)
3509           (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
3510         (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
3511         if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
3512           {
3513             const char
3514               *value;
3515
3516             (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
3517             if (image->colorspace == YCbCrColorspace)
3518               {
3519                 const char
3520                   *sampling_factor;
3521
3522                 GeometryInfo
3523                   geometry_info;
3524
3525                 MagickStatusType
3526                   flags;
3527
3528                 sampling_factor=(const char *) NULL;
3529                 value=GetImageProperty(image,"jpeg:sampling-factor",exception);
3530                 if (value != (char *) NULL)
3531                   {
3532                     sampling_factor=value;
3533                     if (image->debug != MagickFalse)
3534                       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
3535                         "  Input sampling-factors=%s",sampling_factor);
3536                   }
3537                 if (image_info->sampling_factor != (char *) NULL)
3538                   sampling_factor=image_info->sampling_factor;
3539                 if (sampling_factor != (const char *) NULL)
3540                   {
3541                     flags=ParseGeometry(sampling_factor,&geometry_info);
3542                     if ((flags & SigmaValue) == 0)
3543                       geometry_info.sigma=geometry_info.rho;
3544                     (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
3545                       geometry_info.rho,(uint16) geometry_info.sigma);
3546                   }
3547                 }
3548           }
3549         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3550           &bits_per_sample);
3551         if (bits_per_sample == 12)
3552           (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
3553 #endif
3554         break;
3555       }
3556       case COMPRESSION_ADOBE_DEFLATE:
3557       {
3558         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3559           &bits_per_sample);
3560         if (((photometric == PHOTOMETRIC_RGB) ||
3561              (photometric == PHOTOMETRIC_MINISBLACK)) &&
3562             ((bits_per_sample == 8) || (bits_per_sample == 16)))
3563           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3564         (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
3565           image_info->quality == UndefinedCompressionQuality ? 7 :
3566           MagickMin((ssize_t) image_info->quality/10,9)));
3567         break;
3568       }
3569       case COMPRESSION_CCITTFAX3:
3570       {
3571         /*
3572           Byte-aligned EOL.
3573         */
3574         (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
3575         break;
3576       }
3577       case COMPRESSION_CCITTFAX4:
3578         break;
3579 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3580       case COMPRESSION_LZMA:
3581       {
3582         if (((photometric == PHOTOMETRIC_RGB) ||
3583              (photometric == PHOTOMETRIC_MINISBLACK)) &&
3584             ((bits_per_sample == 8) || (bits_per_sample == 16)))
3585           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3586         (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
3587           image_info->quality == UndefinedCompressionQuality ? 7 :
3588           MagickMin((ssize_t) image_info->quality/10,9)));
3589         break;
3590       }
3591 #endif
3592       case COMPRESSION_LZW:
3593       {
3594         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3595           &bits_per_sample);
3596         if (((photometric == PHOTOMETRIC_RGB) ||
3597              (photometric == PHOTOMETRIC_MINISBLACK)) &&
3598             ((bits_per_sample == 8) || (bits_per_sample == 16)))
3599           (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3600         break;
3601       }
3602       default:
3603         break;
3604     }
3605     if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
3606       {
3607         unsigned short
3608           units;
3609
3610         /*
3611           Set image resolution.
3612         */
3613         units=RESUNIT_NONE;
3614         if (image->units == PixelsPerInchResolution)
3615           units=RESUNIT_INCH;
3616         if (image->units == PixelsPerCentimeterResolution)
3617           units=RESUNIT_CENTIMETER;
3618         (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
3619         (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
3620         (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
3621         if ((image->page.x < 0) || (image->page.y < 0))
3622           (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3623             "TIFF: negative image positions unsupported","%s",image->filename);
3624         if ((image->page.x > 0) && (image->resolution.x > 0.0))
3625           {
3626             /*
3627               Set horizontal image position.
3628             */
3629             (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
3630               image->resolution.x);
3631           }
3632         if ((image->page.y > 0) && (image->resolution.y > 0.0))
3633           {
3634             /*
3635               Set vertical image position.
3636             */
3637             (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
3638               image->resolution.y);
3639           }
3640       }
3641     if (image->chromaticity.white_point.x != 0.0)
3642       {
3643         float
3644           chromaticity[6];
3645
3646         /*
3647           Set image chromaticity.
3648         */
3649         chromaticity[0]=(float) image->chromaticity.red_primary.x;
3650         chromaticity[1]=(float) image->chromaticity.red_primary.y;
3651         chromaticity[2]=(float) image->chromaticity.green_primary.x;
3652         chromaticity[3]=(float) image->chromaticity.green_primary.y;
3653         chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3654         chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3655         (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3656         chromaticity[0]=(float) image->chromaticity.white_point.x;
3657         chromaticity[1]=(float) image->chromaticity.white_point.y;
3658         (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3659       }
3660     if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3661         (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3662       {
3663         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3664         if (image->scene != 0)
3665           (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3666             GetImageListLength(image));
3667       }
3668     if (image->orientation != UndefinedOrientation)
3669       (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3670     (void) TIFFSetProfiles(tiff,image);
3671     {
3672       uint16
3673         page,
3674         pages;
3675
3676       page=(uint16) scene;
3677       pages=(uint16) GetImageListLength(image);
3678       if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3679           (image_info->adjoin != MagickFalse) && (pages > 1))
3680         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3681       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3682     }
3683     (void) TIFFSetProperties(tiff,image_info,image,exception);
3684 DisableMSCWarning(4127)
3685     if (0)
3686 RestoreMSCWarning
3687       (void) TIFFSetEXIFProperties(tiff,image,exception);
3688     /*
3689       Write image scanlines.
3690     */
3691     if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3692       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3693     quantum_info->endian=LSBEndian;
3694     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
3695     tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);
3696     switch (photometric)
3697     {
3698       case PHOTOMETRIC_CIELAB:
3699       case PHOTOMETRIC_YCBCR:
3700       case PHOTOMETRIC_RGB:
3701       {
3702         /*
3703           RGB TIFF image.
3704         */
3705         switch (image_info->interlace)
3706         {
3707           case NoInterlace:
3708           default:
3709           {
3710             quantum_type=RGBQuantum;
3711             if (image->alpha_trait != UndefinedPixelTrait)
3712               quantum_type=RGBAQuantum;
3713             for (y=0; y < (ssize_t) image->rows; y++)
3714             {
3715               register const Quantum
3716                 *magick_restrict p;
3717
3718               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3719               if (p == (const Quantum *) NULL)
3720                 break;
3721               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3722                 quantum_type,pixels,exception);
3723               (void) length;
3724               if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3725                 break;
3726               if (image->previous == (Image *) NULL)
3727                 {
3728                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3729                     y,image->rows);
3730                   if (status == MagickFalse)
3731                     break;
3732                 }
3733             }
3734             break;
3735           }
3736           case PlaneInterlace:
3737           case PartitionInterlace:
3738           {
3739             /*
3740               Plane interlacing:  RRRRRR...GGGGGG...BBBBBB...
3741             */
3742             for (y=0; y < (ssize_t) image->rows; y++)
3743             {
3744               register const Quantum
3745                 *magick_restrict p;
3746
3747               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3748               if (p == (const Quantum *) NULL)
3749                 break;
3750               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3751                 RedQuantum,pixels,exception);
3752               if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3753                 break;
3754             }
3755             if (image->previous == (Image *) NULL)
3756               {
3757                 status=SetImageProgress(image,SaveImageTag,100,400);
3758                 if (status == MagickFalse)
3759                   break;
3760               }
3761             for (y=0; y < (ssize_t) image->rows; y++)
3762             {
3763               register const Quantum
3764                 *magick_restrict p;
3765
3766               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3767               if (p == (const Quantum *) NULL)
3768                 break;
3769               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3770                 GreenQuantum,pixels,exception);
3771               if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3772                 break;
3773             }
3774             if (image->previous == (Image *) NULL)
3775               {
3776                 status=SetImageProgress(image,SaveImageTag,200,400);
3777                 if (status == MagickFalse)
3778                   break;
3779               }
3780             for (y=0; y < (ssize_t) image->rows; y++)
3781             {
3782               register const Quantum
3783                 *magick_restrict p;
3784
3785               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3786               if (p == (const Quantum *) NULL)
3787                 break;
3788               length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3789                 BlueQuantum,pixels,exception);
3790               if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3791                 break;
3792             }
3793             if (image->previous == (Image *) NULL)
3794               {
3795                 status=SetImageProgress(image,SaveImageTag,300,400);
3796                 if (status == MagickFalse)
3797                   break;
3798               }
3799             if (image->alpha_trait != UndefinedPixelTrait)
3800               for (y=0; y < (ssize_t) image->rows; y++)
3801               {
3802                 register const Quantum
3803                   *magick_restrict p;
3804
3805                 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3806                 if (p == (const Quantum *) NULL)
3807                   break;
3808                 length=ExportQuantumPixels(image,(CacheView *) NULL,
3809                   quantum_info,AlphaQuantum,pixels,exception);
3810                 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3811                   break;
3812               }
3813             if (image->previous == (Image *) NULL)
3814               {
3815                 status=SetImageProgress(image,SaveImageTag,400,400);
3816                 if (status == MagickFalse)
3817                   break;
3818               }
3819             break;
3820           }
3821         }
3822         break;
3823       }
3824       case PHOTOMETRIC_SEPARATED:
3825       {
3826         /*
3827           CMYK TIFF image.
3828         */
3829         quantum_type=CMYKQuantum;
3830         if (image->alpha_trait != UndefinedPixelTrait)
3831           quantum_type=CMYKAQuantum;
3832         if (image->colorspace != CMYKColorspace)
3833           (void) TransformImageColorspace(image,CMYKColorspace,exception);
3834         for (y=0; y < (ssize_t) image->rows; y++)
3835         {
3836           register const Quantum
3837             *magick_restrict p;
3838
3839           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3840           if (p == (const Quantum *) NULL)
3841             break;
3842           length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3843             quantum_type,pixels,exception);
3844           if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3845             break;
3846           if (image->previous == (Image *) NULL)
3847             {
3848               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3849                 image->rows);
3850               if (status == MagickFalse)
3851                 break;
3852             }
3853         }
3854         break;
3855       }
3856       case PHOTOMETRIC_PALETTE:
3857       {
3858         uint16
3859           *blue,
3860           *green,
3861           *red;
3862
3863         /*
3864           Colormapped TIFF image.
3865         */
3866         red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3867         green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3868         blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3869         if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3870             (blue == (uint16 *) NULL))
3871           ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3872         /*
3873           Initialize TIFF colormap.
3874         */
3875         (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3876         (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3877         (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3878         for (i=0; i < (ssize_t) image->colors; i++)
3879         {
3880           red[i]=ScaleQuantumToShort(image->colormap[i].red);
3881           green[i]=ScaleQuantumToShort(image->colormap[i].green);
3882           blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3883         }
3884         (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3885         red=(uint16 *) RelinquishMagickMemory(red);
3886         green=(uint16 *) RelinquishMagickMemory(green);
3887         blue=(uint16 *) RelinquishMagickMemory(blue);
3888       }
3889       default:
3890       {
3891         /*
3892           Convert PseudoClass packets to contiguous grayscale scanlines.
3893         */
3894         quantum_type=IndexQuantum;
3895         if (image->alpha_trait != UndefinedPixelTrait)
3896           {
3897             if (photometric != PHOTOMETRIC_PALETTE)
3898               quantum_type=GrayAlphaQuantum;
3899             else
3900               quantum_type=IndexAlphaQuantum;
3901            }
3902          else
3903            if (photometric != PHOTOMETRIC_PALETTE)
3904              quantum_type=GrayQuantum;
3905         for (y=0; y < (ssize_t) image->rows; y++)
3906         {
3907           register const Quantum
3908             *magick_restrict p;
3909
3910           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3911           if (p == (const Quantum *) NULL)
3912             break;
3913           length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3914             quantum_type,pixels,exception);
3915           if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3916             break;
3917           if (image->previous == (Image *) NULL)
3918             {
3919               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3920                 image->rows);
3921               if (status == MagickFalse)
3922                 break;
3923             }
3924         }
3925         break;
3926       }
3927     }
3928     quantum_info=DestroyQuantumInfo(quantum_info);
3929     if (image->colorspace == LabColorspace)
3930       DecodeLabImage(image,exception);
3931     DestroyTIFFInfo(&tiff_info);
3932 DisableMSCWarning(4127)
3933     if (0 && (image_info->verbose != MagickFalse))
3934 RestoreMSCWarning
3935       TIFFPrintDirectory(tiff,stdout,MagickFalse);
3936     (void) TIFFWriteDirectory(tiff);
3937     image=SyncNextImageInList(image);
3938     if (image == (Image *) NULL)
3939       break;
3940     status=SetImageProgress(image,SaveImagesTag,scene++,
3941       GetImageListLength(image));
3942     if (status == MagickFalse)
3943       break;
3944   } while (image_info->adjoin != MagickFalse);
3945   TIFFClose(tiff);
3946   return(MagickTrue);
3947 }
3948 #endif