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