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