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