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