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