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