2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % TTTTT IIIII FFFFF FFFFF %
13 % Read/Write TIFF Image Format %
20 % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % https://imagemagick.org/script/license.php %
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. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
43 #define JPEG_SUPPORT 1
45 #include "MagickCore/studio.h"
46 #include "MagickCore/artifact.h"
47 #include "MagickCore/attribute.h"
48 #include "MagickCore/blob.h"
49 #include "MagickCore/blob-private.h"
50 #include "MagickCore/cache.h"
51 #include "MagickCore/channel.h"
52 #include "MagickCore/color.h"
53 #include "MagickCore/color-private.h"
54 #include "MagickCore/colormap.h"
55 #include "MagickCore/colorspace.h"
56 #include "MagickCore/colorspace-private.h"
57 #include "MagickCore/constitute.h"
58 #include "MagickCore/enhance.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/geometry.h"
62 #include "MagickCore/image.h"
63 #include "MagickCore/image-private.h"
64 #include "MagickCore/list.h"
65 #include "MagickCore/log.h"
66 #include "MagickCore/magick.h"
67 #include "MagickCore/memory_.h"
68 #include "MagickCore/memory-private.h"
69 #include "MagickCore/module.h"
70 #include "MagickCore/monitor.h"
71 #include "MagickCore/monitor-private.h"
72 #include "MagickCore/option.h"
73 #include "MagickCore/pixel-accessor.h"
74 #include "MagickCore/pixel-private.h"
75 #include "MagickCore/property.h"
76 #include "MagickCore/quantum.h"
77 #include "MagickCore/quantum-private.h"
78 #include "MagickCore/profile.h"
79 #include "MagickCore/resize.h"
80 #include "MagickCore/resource_.h"
81 #include "MagickCore/semaphore.h"
82 #include "MagickCore/splay-tree.h"
83 #include "MagickCore/static.h"
84 #include "MagickCore/statistic.h"
85 #include "MagickCore/string_.h"
86 #include "MagickCore/string-private.h"
87 #include "MagickCore/thread_.h"
88 #include "MagickCore/token.h"
89 #include "MagickCore/utility.h"
90 #if defined(MAGICKCORE_TIFF_DELEGATE)
91 # if defined(MAGICKCORE_HAVE_TIFFCONF_H)
92 # include <tiffconf.h>
96 # if !defined(COMPRESSION_ADOBE_DEFLATE)
97 # define COMPRESSION_ADOBE_DEFLATE 8
99 # if !defined(PREDICTOR_HORIZONTAL)
100 # define PREDICTOR_HORIZONTAL 2
102 # if !defined(TIFFTAG_COPYRIGHT)
103 # define TIFFTAG_COPYRIGHT 33432
105 # if !defined(TIFFTAG_OPIIMAGEID)
106 # define TIFFTAG_OPIIMAGEID 32781
108 # if defined(COMPRESSION_ZSTD) && defined(MAGICKCORE_ZSTD_DELEGATE)
111 #include "psd-private.h"
114 Typedef declarations.
118 ReadSingleSampleMethod,
128 typedef struct _PhotoshopProfile
142 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
143 typedef struct _ExifInfo
154 static const ExifInfo
156 { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
157 { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
158 { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
159 { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
160 { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
161 { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
162 { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
163 { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
164 { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
165 { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
166 { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
167 { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
168 { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
169 { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
170 { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
171 { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
172 { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
173 { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
174 { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
175 { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
176 { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
177 { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
178 { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
179 { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
180 { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
181 { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
182 { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
183 { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
184 { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
185 { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
186 { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
187 { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
188 { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
189 { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
190 { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
191 { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
192 { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 2, "exif:SubjectLocation" },
193 { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
194 { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
195 { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
196 { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
197 { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
198 { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
199 { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
200 { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
201 { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
202 { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
203 { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
204 { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
205 { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
206 { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
207 { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
208 { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
209 { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
210 { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
211 { 0, 0, 0, (char *) NULL }
218 static MagickThreadKey
222 *tiff_semaphore = (SemaphoreInfo *) NULL;
224 static TIFFErrorHandler
228 static volatile MagickBooleanType
229 instantiate_key = MagickFalse;
232 Forward declarations.
235 ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
237 static MagickBooleanType
238 WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
239 WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
240 WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
242 static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset,
243 const int whence,void *user_data)
248 profile=(PhotoshopProfile *) user_data;
256 profile->offset=offset;
261 if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) ||
262 ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset))))
267 if ((profile->offset+offset) < 0)
269 profile->offset+=offset;
274 if (((MagickOffsetType) profile->length+offset) < 0)
276 profile->offset=profile->length+offset;
281 return(profile->offset);
284 static MagickOffsetType TIFFTellCustomStream(void *user_data)
289 profile=(PhotoshopProfile *) user_data;
290 return(profile->offset);
293 static void InitPSDInfo(const Image *image,PSDInfo *info)
296 info->columns=image->columns;
297 info->rows=image->rows;
298 info->mode=10; /* Set the mode to a value that won't change the colorspace */
300 info->min_channels=1U;
301 info->has_merged_image=MagickFalse;
302 if (image->storage_class == PseudoClass)
303 info->mode=2; /* indexed mode */
306 info->channels=(unsigned short) image->number_channels;
307 info->min_channels=info->channels;
308 if (image->alpha_trait == BlendPixelTrait)
309 info->min_channels--;
315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
323 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
325 % IsTIFF() returns MagickTrue if the image format type, identified by the
326 % magick string, is TIFF.
328 % The format of the IsTIFF method is:
330 % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
332 % A description of each parameter follows:
334 % o magick: compare image format pattern against these bytes.
336 % o length: Specifies the length of the magick string.
339 static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
343 if (memcmp(magick,"\115\115\000\052",4) == 0)
345 if (memcmp(magick,"\111\111\052\000",4) == 0)
347 #if defined(TIFF_VERSION_BIG)
350 if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
352 if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
358 #if defined(MAGICKCORE_TIFF_DELEGATE)
360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
364 % R e a d G R O U P 4 I m a g e %
368 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
370 % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
371 % allocates the memory necessary for the new Image structure and returns a
372 % pointer to the new image.
374 % The format of the ReadGROUP4Image method is:
376 % Image *ReadGROUP4Image(const ImageInfo *image_info,
377 % ExceptionInfo *exception)
379 % A description of each parameter follows:
381 % o image_info: the image info.
383 % o exception: return any errors or warnings in this structure.
387 static inline size_t WriteLSBLong(FILE *file,const unsigned int value)
392 buffer[0]=(unsigned char) value;
393 buffer[1]=(unsigned char) (value >> 8);
394 buffer[2]=(unsigned char) (value >> 16);
395 buffer[3]=(unsigned char) (value >> 24);
396 return(fwrite(buffer,1,4,file));
399 static Image *ReadGROUP4Image(const ImageInfo *image_info,
400 ExceptionInfo *exception)
403 filename[MagickPathExtent];
431 assert(image_info != (const ImageInfo *) NULL);
432 assert(image_info->signature == MagickCoreSignature);
433 if (image_info->debug != MagickFalse)
434 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
435 image_info->filename);
436 assert(exception != (ExceptionInfo *) NULL);
437 assert(exception->signature == MagickCoreSignature);
438 image=AcquireImage(image_info,exception);
439 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
440 if (status == MagickFalse)
442 image=DestroyImageList(image);
443 return((Image *) NULL);
446 Write raw CCITT Group 4 wrapped as a TIFF image file.
449 unique_file=AcquireUniqueFileResource(filename);
450 if (unique_file != -1)
451 file=fdopen(unique_file,"wb");
452 if ((unique_file == -1) || (file == (FILE *) NULL))
453 ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
454 length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
456 ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
457 length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
458 length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
459 length=WriteLSBLong(file,(unsigned int) image->columns);
460 length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
461 length=WriteLSBLong(file,(unsigned int) image->rows);
462 length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
463 length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
464 length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
465 length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
466 strip_offset=10+(12*14)+4+8;
467 length=WriteLSBLong(file,(unsigned int) strip_offset);
468 length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
469 length=WriteLSBLong(file,(unsigned int) image_info->orientation);
470 length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
471 length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
472 length=WriteLSBLong(file,(unsigned int) image->rows);
473 length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
474 offset=(ssize_t) ftell(file)-4;
475 length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
476 length=WriteLSBLong(file,(unsigned int) (strip_offset-8));
477 length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
478 length=WriteLSBLong(file,(unsigned int) (strip_offset-8));
479 length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
480 length=fwrite("\000\000\000\000",1,4,file);
481 length=WriteLSBLong(file,(unsigned int) image->resolution.x);
482 length=WriteLSBLong(file,1);
484 for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
485 if (fputc(c,file) != c)
487 offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
488 length=WriteLSBLong(file,(unsigned int) length);
489 if (ferror(file) != 0)
492 ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
495 (void) CloseBlob(image);
496 image=DestroyImage(image);
500 read_info=CloneImageInfo((ImageInfo *) NULL);
501 (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
502 image=ReadTIFFImage(read_info,exception);
503 read_info=DestroyImageInfo(read_info);
504 if (image != (Image *) NULL)
506 (void) CopyMagickString(image->filename,image_info->filename,
508 (void) CopyMagickString(image->magick_filename,image_info->filename,
510 (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
512 (void) RelinquishUniqueFileResource(filename);
513 if (status == MagickFalse)
514 image=DestroyImage(image);
519 #if defined(MAGICKCORE_TIFF_DELEGATE)
521 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
525 % R e a d T I F F I m a g e %
529 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
531 % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
532 % memory necessary for the new Image structure and returns a pointer to the
535 % The format of the ReadTIFFImage method is:
537 % Image *ReadTIFFImage(const ImageInfo *image_info,
538 % ExceptionInfo *exception)
540 % A description of each parameter follows:
542 % o image_info: the image info.
544 % o exception: return any errors or warnings in this structure.
548 static inline unsigned char ClampYCC(double value)
552 return((unsigned char)0);
554 return((unsigned char)255);
555 return((unsigned char)(value));
558 static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
570 image_view=AcquireAuthenticCacheView(image,exception);
571 for (y=0; y < (ssize_t) image->rows; y++)
579 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
580 if (q == (Quantum *) NULL)
585 for (x=0; x < (ssize_t) image->columns; x++)
591 a=QuantumScale*GetPixela(image,q)+0.5;
594 b=QuantumScale*GetPixelb(image,q)+0.5;
597 SetPixela(image,QuantumRange*a,q);
598 SetPixelb(image,QuantumRange*b,q);
599 q+=GetPixelChannels(image);
601 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
607 image_view=DestroyCacheView(image_view);
611 static MagickBooleanType ReadProfile(Image *image,const char *name,
612 const unsigned char *datum,ssize_t length,ExceptionInfo *exception)
622 profile=BlobToStringInfo(datum,(size_t) length);
623 if (profile == (StringInfo *) NULL)
624 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
626 status=SetImageProfile(image,name,profile,exception);
627 profile=DestroyStringInfo(profile);
628 if (status == MagickFalse)
629 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
634 #if defined(__cplusplus) || defined(c_plusplus)
638 static int TIFFCloseBlob(thandle_t image)
640 (void) CloseBlob((Image *) image);
644 static void TIFFErrors(const char *,const char *,va_list)
645 magick_attribute((__format__ (__printf__,2,0)));
647 static void TIFFErrors(const char *module,const char *format,va_list error)
650 message[MagickPathExtent];
655 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
656 (void) vsnprintf(message,MagickPathExtent-2,format,error);
658 (void) vsprintf(message,format,error);
660 message[MaxTextExtent-2]='\0';
661 (void) ConcatenateMagickString(message,".",MagickPathExtent);
662 exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
663 if (exception != (ExceptionInfo *) NULL)
664 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
668 static toff_t TIFFGetBlobSize(thandle_t image)
670 return((toff_t) GetBlobSize((Image *) image));
673 static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
682 #if defined(TIFFTAG_ICCPROFILE)
683 if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
684 (profile != (unsigned char *) NULL))
685 (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
687 #if defined(TIFFTAG_PHOTOSHOP)
688 if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
689 (profile != (unsigned char *) NULL))
690 (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
692 #if defined(TIFFTAG_RICHTIFFIPTC)
693 if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
694 (profile != (unsigned char *) NULL))
696 if (TIFFIsByteSwapped(tiff) != 0)
697 TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
698 (void) ReadProfile(image,"iptc",profile,4L*length,exception);
701 #if defined(TIFFTAG_XMLPACKET)
702 if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
703 (profile != (unsigned char *) NULL))
705 (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
706 if (strstr((char *) profile,"dc:format=\"image/dng\"") != (char *) NULL)
707 (void) CopyMagickString(image->magick,"DNG",MagickPathExtent);
710 if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
711 (profile != (unsigned char *) NULL))
712 (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,
714 if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
715 (profile != (unsigned char *) NULL))
716 (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
719 static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
722 message[MagickPathExtent],
729 if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) &&
730 (text != (char *) NULL))
731 (void) SetImageProperty(image,"tiff:artist",text,exception);
732 if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) &&
733 (text != (char *) NULL))
734 (void) SetImageProperty(image,"tiff:copyright",text,exception);
735 if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) &&
736 (text != (char *) NULL))
737 (void) SetImageProperty(image,"tiff:timestamp",text,exception);
738 if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) &&
739 (text != (char *) NULL))
740 (void) SetImageProperty(image,"tiff:document",text,exception);
741 if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) &&
742 (text != (char *) NULL))
743 (void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
744 if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) &&
745 (text != (char *) NULL))
746 (void) SetImageProperty(image,"comment",text,exception);
747 if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) &&
748 (text != (char *) NULL))
749 (void) SetImageProperty(image,"tiff:make",text,exception);
750 if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) &&
751 (text != (char *) NULL))
752 (void) SetImageProperty(image,"tiff:model",text,exception);
753 if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) &&
754 (text != (char *) NULL))
756 if (count >= MagickPathExtent)
757 count=MagickPathExtent-1;
758 (void) CopyMagickString(message,text,count+1);
759 (void) SetImageProperty(image,"tiff:image-id",message,exception);
761 if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) &&
762 (text != (char *) NULL))
763 (void) SetImageProperty(image,"label",text,exception);
764 if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) &&
765 (text != (char *) NULL))
766 (void) SetImageProperty(image,"tiff:software",text,exception);
767 if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL))
769 if (count >= MagickPathExtent)
770 count=MagickPathExtent-1;
771 (void) CopyMagickString(message,text,count+1);
772 (void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
774 if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL))
776 if (count >= MagickPathExtent)
777 count=MagickPathExtent-1;
778 (void) CopyMagickString(message,text,count+1);
779 (void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
781 if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
786 (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
792 (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
797 (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
805 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
806 ExceptionInfo *exception)
808 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
810 value[MagickPathExtent];
818 #if defined(TIFF_VERSION_BIG)
826 *sans[2] = { NULL, NULL };
829 Read EXIF properties.
832 if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
834 directory=TIFFCurrentDirectory(tiff);
835 if (TIFFReadEXIFDirectory(tiff,offset) != 1)
837 TIFFSetDirectory(tiff,directory);
840 for (i=0; exif_info[i].tag != 0; i++)
843 switch (exif_info[i].type)
851 if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) &&
852 (ascii != (char *) NULL) && (*ascii != '\0'))
853 (void) CopyMagickString(value,ascii,MagickPathExtent);
858 if (exif_info[i].variable_length == 0)
864 if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1)
865 (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty);
867 else if (exif_info[i].variable_length == 2)
873 if ((TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1) &&
874 (shorty != (uint16 *) NULL))
875 (void) FormatLocaleString(value,MagickPathExtent,"%d",*shorty);
888 tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
890 if (tiff_status == 1)
891 (void) FormatLocaleString(value,MagickPathExtent,"%d",
892 shorty_num != 0 ? shorty[0] : 0);
902 if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1)
903 (void) FormatLocaleString(value,MagickPathExtent,"%d",longy);
906 #if defined(TIFF_VERSION_BIG)
913 if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1)
914 (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
915 ((MagickOffsetType) long8y));
927 if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1)
928 (void) FormatLocaleString(value,MagickPathExtent,"%g",(double)
938 if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1)
939 (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley);
946 (void) SetImageProperty(image,exif_info[i].property,value,exception);
948 TIFFSetDirectory(tiff,directory);
955 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
957 *base=(tdata_t *) GetBlobStreamData((Image *) image);
958 if (*base != (tdata_t *) NULL)
959 *size=(toff_t) GetBlobSize((Image *) image);
960 if (*base != (tdata_t *) NULL)
965 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
970 count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
971 (unsigned char *) data);
975 static int32 TIFFReadPixels(TIFF *tiff,const tsample_t sample,const ssize_t row,
981 status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
985 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
987 return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
990 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
997 static void TIFFWarnings(const char *,const char *,va_list)
998 magick_attribute((__format__ (__printf__,2,0)));
1000 static void TIFFWarnings(const char *module,const char *format,va_list warning)
1003 message[MagickPathExtent];
1008 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
1009 (void) vsnprintf(message,MagickPathExtent-2,format,warning);
1011 (void) vsprintf(message,format,warning);
1013 message[MaxTextExtent-2]='\0';
1014 (void) ConcatenateMagickString(message,".",MagickPathExtent);
1015 exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
1016 if (exception != (ExceptionInfo *) NULL)
1017 (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
1018 message,"`%s'",module);
1021 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
1026 count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
1027 (unsigned char *) data);
1031 static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
1032 uint16 bits_per_sample,uint16 samples_per_pixel)
1034 #define BUFFER_SIZE 2048
1046 #if defined(TIFF_VERSION_BIG)
1054 buffer[BUFFER_SIZE+32];
1060 Only support 8 bit for now.
1062 if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
1063 (samples_per_pixel != 4))
1064 return(ReadGenericMethod);
1066 Search for Adobe APP14 JPEG marker.
1069 if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value) || (value == NULL))
1070 return(ReadRGBAMethod);
1071 position=TellBlob(image);
1072 offset=(MagickOffsetType) (value[0]);
1073 if (SeekBlob(image,offset,SEEK_SET) != offset)
1074 return(ReadRGBAMethod);
1075 method=ReadRGBAMethod;
1076 if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
1078 for (i=0; i < BUFFER_SIZE; i++)
1080 while (i < BUFFER_SIZE)
1082 if (buffer[i++] == 255)
1085 while (i < BUFFER_SIZE)
1087 if (buffer[++i] != 255)
1090 if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
1092 length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
1093 (unsigned int) buffer[i+1]) & 0xffff);
1094 if (i+(size_t) length >= BUFFER_SIZE)
1096 if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
1100 /* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
1101 if (buffer[i+13] == 2)
1102 method=ReadYCCKMethod;
1108 (void) SeekBlob(image,position,SEEK_SET);
1112 static ssize_t TIFFReadCustomStream(unsigned char *data,const size_t count,
1126 profile=(PhotoshopProfile *) user_data;
1127 remaining=(MagickOffsetType) profile->length-profile->offset;
1130 total=MagickMin(count, (size_t) remaining);
1131 (void) memcpy(data,profile->data->datum+profile->offset,total);
1132 profile->offset+=total;
1136 static CustomStreamInfo *TIFFAcquireCustomStreamForReading(
1137 PhotoshopProfile *profile,ExceptionInfo *exception)
1142 custom_stream=AcquireCustomStreamInfo(exception);
1143 if (custom_stream == (CustomStreamInfo *) NULL)
1144 return(custom_stream);
1145 SetCustomStreamData(custom_stream,(void *) profile);
1146 SetCustomStreamReader(custom_stream,TIFFReadCustomStream);
1147 SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream);
1148 SetCustomStreamTeller(custom_stream,TIFFTellCustomStream);
1149 return(custom_stream);
1152 static void TIFFReadPhotoshopLayers(const ImageInfo *image_info,Image *image,
1153 ExceptionInfo *exception)
1179 if (GetImageListLength(image) != 1)
1181 if ((image_info->number_scenes == 1) && (image_info->scene == 0))
1183 option=GetImageOption(image_info,"tiff:ignore-layers");
1184 if (option != (const char * ) NULL)
1186 profile=GetImageProfile(image,"tiff:37724");
1187 if (profile == (const StringInfo *) NULL)
1189 for (i=0; i < (ssize_t) profile->length-8; i++)
1191 if (LocaleNCompare((const char *) (profile->datum+i),
1192 image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
1195 if ((LocaleNCompare((const char *) (profile->datum+i),
1196 image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
1197 (LocaleNCompare((const char *) (profile->datum+i),
1198 image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
1199 (LocaleNCompare((const char *) (profile->datum+i),
1200 image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
1201 (LocaleNCompare((const char *) (profile->datum+i),
1202 image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
1206 if (i >= (ssize_t) (profile->length-8))
1208 photoshop_profile.data=(StringInfo *) profile;
1209 photoshop_profile.length=profile->length;
1210 custom_stream=TIFFAcquireCustomStreamForReading(&photoshop_profile,exception);
1211 if (custom_stream == (CustomStreamInfo *) NULL)
1213 layers=CloneImage(image,0,0,MagickTrue,exception);
1214 if (layers == (Image *) NULL)
1216 custom_stream=DestroyCustomStreamInfo(custom_stream);
1219 (void) DeleteImageProfile(layers,"tiff:37724");
1220 AttachCustomStream(layers->blob,custom_stream);
1221 SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
1222 InitPSDInfo(layers,&info);
1223 clone_info=CloneImageInfo(image_info);
1224 clone_info->number_scenes=0;
1225 (void) ReadPSDLayers(layers,clone_info,&info,exception);
1226 clone_info=DestroyImageInfo(clone_info);
1227 DeleteImageFromList(&layers);
1228 if (layers != (Image *) NULL)
1230 SetImageArtifact(image,"tiff:has-layers","true");
1231 AppendImageToList(&image,layers);
1232 while (layers != (Image *) NULL)
1234 SetImageArtifact(layers,"tiff:has-layers","true");
1235 DetachBlob(layers->blob);
1236 layers=GetNextImageInList(layers);
1239 custom_stream=DestroyCustomStreamInfo(custom_stream);
1242 #if defined(__cplusplus) || defined(c_plusplus)
1246 static Image *ReadTIFFImage(const ImageInfo *image_info,
1247 ExceptionInfo *exception)
1249 #define ThrowTIFFException(severity,message) \
1251 if (pixel_info != (MemoryInfo *) NULL) \
1252 pixel_info=RelinquishVirtualMemory(pixel_info); \
1253 if (quantum_info != (QuantumInfo *) NULL) \
1254 quantum_info=DestroyQuantumInfo(quantum_info); \
1256 ThrowReaderException(severity,message); \
1283 *pixel_info = (MemoryInfo *) NULL;
1334 assert(image_info != (const ImageInfo *) NULL);
1335 assert(image_info->signature == MagickCoreSignature);
1336 if (image_info->debug != MagickFalse)
1337 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
1338 image_info->filename);
1339 assert(exception != (ExceptionInfo *) NULL);
1340 assert(exception->signature == MagickCoreSignature);
1341 image=AcquireImage(image_info,exception);
1342 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
1343 if (status == MagickFalse)
1345 image=DestroyImageList(image);
1346 return((Image *) NULL);
1348 (void) SetMagickThreadValue(tiff_exception,exception);
1349 tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
1350 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
1352 if (tiff == (TIFF *) NULL)
1354 image=DestroyImageList(image);
1355 return((Image *) NULL);
1357 if (exception->severity > ErrorException)
1360 image=DestroyImageList(image);
1361 return((Image *) NULL);
1363 if (image_info->number_scenes != 0)
1366 Generate blank images for subimage specification (e.g. image.tif[4].
1367 We need to check the number of directores because it is possible that
1368 the subimage(s) are stored in the photoshop profile.
1370 if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))
1372 for (i=0; i < (ssize_t) image_info->scene; i++)
1374 status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1375 if (status == MagickFalse)
1378 image=DestroyImageList(image);
1379 return((Image *) NULL);
1381 AcquireNextImage(image_info,image,exception);
1382 if (GetNextImageInList(image) == (Image *) NULL)
1385 image=DestroyImageList(image);
1386 return((Image *) NULL);
1388 image=SyncNextImageInList(image);
1392 more_frames=MagickTrue;
1395 DisableMSCWarning(4127)
1396 if (0 && (image_info->verbose != MagickFalse))
1397 TIFFPrintDirectory(tiff,stdout,MagickFalse);
1399 photometric=PHOTOMETRIC_RGB;
1400 if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
1401 (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
1402 (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) ||
1403 (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
1404 (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
1405 (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
1406 (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
1407 (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
1408 (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
1409 (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
1410 (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1))
1413 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1415 if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) &&
1416 ((bits_per_sample <= 0) || (bits_per_sample > 32)))
1419 ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
1421 if (sample_format == SAMPLEFORMAT_IEEEFP)
1422 (void) SetImageProperty(image,"quantum:format","floating-point",
1424 switch (photometric)
1426 case PHOTOMETRIC_MINISBLACK:
1428 (void) SetImageProperty(image,"tiff:photometric","min-is-black",
1432 case PHOTOMETRIC_MINISWHITE:
1434 (void) SetImageProperty(image,"tiff:photometric","min-is-white",
1438 case PHOTOMETRIC_PALETTE:
1440 (void) SetImageProperty(image,"tiff:photometric","palette",exception);
1443 case PHOTOMETRIC_RGB:
1445 (void) SetImageProperty(image,"tiff:photometric","RGB",exception);
1448 case PHOTOMETRIC_CIELAB:
1450 (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
1453 case PHOTOMETRIC_LOGL:
1455 (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)",
1459 case PHOTOMETRIC_LOGLUV:
1461 (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception);
1464 #if defined(PHOTOMETRIC_MASK)
1465 case PHOTOMETRIC_MASK:
1467 (void) SetImageProperty(image,"tiff:photometric","MASK",exception);
1471 case PHOTOMETRIC_SEPARATED:
1473 (void) SetImageProperty(image,"tiff:photometric","separated",exception);
1476 case PHOTOMETRIC_YCBCR:
1478 (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
1483 (void) SetImageProperty(image,"tiff:photometric","unknown",exception);
1487 if (image->debug != MagickFalse)
1489 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
1490 (unsigned int) width,(unsigned int) height);
1491 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
1493 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1494 "Bits per sample: %u",bits_per_sample);
1495 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1496 "Min sample value: %u",min_sample_value);
1497 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1498 "Max sample value: %u",max_sample_value);
1499 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
1500 "interpretation: %s",GetImageProperty(image,"tiff:photometric",
1503 image->columns=(size_t) width;
1504 image->rows=(size_t) height;
1505 image->depth=(size_t) bits_per_sample;
1506 if (image->debug != MagickFalse)
1507 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
1508 (double) image->depth);
1509 image->endian=MSBEndian;
1510 if (endian == FILLORDER_LSB2MSB)
1511 image->endian=LSBEndian;
1512 #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
1513 if (TIFFIsBigEndian(tiff) == 0)
1515 (void) SetImageProperty(image,"tiff:endian","lsb",exception);
1516 image->endian=LSBEndian;
1520 (void) SetImageProperty(image,"tiff:endian","msb",exception);
1521 image->endian=MSBEndian;
1524 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1525 (photometric == PHOTOMETRIC_MINISWHITE))
1526 SetImageColorspace(image,GRAYColorspace,exception);
1527 if (photometric == PHOTOMETRIC_SEPARATED)
1528 SetImageColorspace(image,CMYKColorspace,exception);
1529 if (photometric == PHOTOMETRIC_CIELAB)
1530 SetImageColorspace(image,LabColorspace,exception);
1531 TIFFGetProfiles(tiff,image,exception);
1532 TIFFGetProperties(tiff,image,exception);
1533 option=GetImageOption(image_info,"tiff:exif-properties");
1534 if (IsStringFalse(option) == MagickFalse) /* enabled by default */
1535 TIFFGetEXIFProperties(tiff,image,exception);
1536 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
1537 &samples_per_pixel);
1538 if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
1539 (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
1541 image->resolution.x=x_resolution;
1542 image->resolution.y=y_resolution;
1544 if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
1546 if (units == RESUNIT_INCH)
1547 image->units=PixelsPerInchResolution;
1548 if (units == RESUNIT_CENTIMETER)
1549 image->units=PixelsPerCentimeterResolution;
1551 if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
1552 (TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
1554 image->page.x=(ssize_t) ceil(x_position*image->resolution.x-0.5);
1555 image->page.y=(ssize_t) ceil(y_position*image->resolution.y-0.5);
1557 if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
1558 image->orientation=(OrientationType) orientation;
1559 if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
1561 if (chromaticity != (float *) NULL)
1563 image->chromaticity.white_point.x=chromaticity[0];
1564 image->chromaticity.white_point.y=chromaticity[1];
1567 if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
1569 if (chromaticity != (float *) NULL)
1571 image->chromaticity.red_primary.x=chromaticity[0];
1572 image->chromaticity.red_primary.y=chromaticity[1];
1573 image->chromaticity.green_primary.x=chromaticity[2];
1574 image->chromaticity.green_primary.y=chromaticity[3];
1575 image->chromaticity.blue_primary.x=chromaticity[4];
1576 image->chromaticity.blue_primary.y=chromaticity[5];
1579 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
1580 if ((compress_tag != COMPRESSION_NONE) &&
1581 (TIFFIsCODECConfigured(compress_tag) == 0))
1584 ThrowReaderException(CoderError,"CompressNotSupported");
1587 switch (compress_tag)
1589 case COMPRESSION_NONE: image->compression=NoCompression; break;
1590 case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1591 case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1592 case COMPRESSION_JPEG:
1594 image->compression=JPEGCompression;
1595 #if defined(JPEG_SUPPORT)
1598 sampling_factor[MagickPathExtent];
1604 tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
1606 if (tiff_status == 1)
1608 (void) FormatLocaleString(sampling_factor,MagickPathExtent,
1609 "%dx%d",horizontal,vertical);
1610 (void) SetImageProperty(image,"jpeg:sampling-factor",
1611 sampling_factor,exception);
1612 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1613 "Sampling Factors: %s",sampling_factor);
1619 case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1620 #if defined(COMPRESSION_LZMA)
1621 case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1623 case COMPRESSION_LZW: image->compression=LZWCompression; break;
1624 case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1625 case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1626 #if defined(COMPRESSION_WEBP)
1627 case COMPRESSION_WEBP: image->compression=WebPCompression; break;
1629 #if defined(COMPRESSION_ZSTD)
1630 case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;
1632 default: image->compression=RLECompression; break;
1634 quantum_info=(QuantumInfo *) NULL;
1635 if ((photometric == PHOTOMETRIC_PALETTE) &&
1636 (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1641 colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1642 if (AcquireImageColormap(image,colors,exception) == MagickFalse)
1645 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1648 value=(unsigned short) image->scene;
1649 if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
1651 if (image->storage_class == PseudoClass)
1662 Initialize colormap.
1664 tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1665 &green_colormap,&blue_colormap);
1666 if (tiff_status == 1)
1668 if ((red_colormap != (uint16 *) NULL) &&
1669 (green_colormap != (uint16 *) NULL) &&
1670 (blue_colormap != (uint16 *) NULL))
1672 range=255; /* might be old style 8-bit colormap */
1673 for (i=0; i < (ssize_t) image->colors; i++)
1674 if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1675 (blue_colormap[i] >= 256))
1680 for (i=0; i < (ssize_t) image->colors; i++)
1682 image->colormap[i].red=ClampToQuantum(((double)
1683 QuantumRange*red_colormap[i])/range);
1684 image->colormap[i].green=ClampToQuantum(((double)
1685 QuantumRange*green_colormap[i])/range);
1686 image->colormap[i].blue=ClampToQuantum(((double)
1687 QuantumRange*blue_colormap[i])/range);
1692 if (image_info->ping != MagickFalse)
1694 if (image_info->number_scenes != 0)
1695 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1697 goto next_tiff_frame;
1699 status=SetImageExtent(image,image->columns,image->rows,exception);
1700 if (status == MagickFalse)
1703 return(DestroyImageList(image));
1705 status=ResetImagePixels(image,exception);
1706 if (status == MagickFalse)
1709 return(DestroyImageList(image));
1712 Allocate memory for the image and pixel buffer.
1714 quantum_info=AcquireQuantumInfo(image_info,image);
1715 if (quantum_info == (QuantumInfo *) NULL)
1716 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1717 if (sample_format == SAMPLEFORMAT_UINT)
1718 status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1719 if (sample_format == SAMPLEFORMAT_INT)
1720 status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1721 if (sample_format == SAMPLEFORMAT_IEEEFP)
1722 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1723 if (status == MagickFalse)
1724 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1726 switch (photometric)
1728 case PHOTOMETRIC_MINISBLACK:
1730 quantum_info->min_is_white=MagickFalse;
1733 case PHOTOMETRIC_MINISWHITE:
1735 quantum_info->min_is_white=MagickTrue;
1741 tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1743 if (tiff_status == 1)
1745 (void) SetImageProperty(image,"tiff:alpha","unspecified",exception);
1746 if (extra_samples == 0)
1748 if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1749 image->alpha_trait=BlendPixelTrait;
1752 for (i=0; i < extra_samples; i++)
1754 image->alpha_trait=BlendPixelTrait;
1755 if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1757 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
1758 (void) SetImageProperty(image,"tiff:alpha","associated",
1762 if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
1764 SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1765 (void) SetImageProperty(image,"tiff:alpha","unassociated",
1770 if (image->alpha_trait != UndefinedPixelTrait)
1771 (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
1772 method=ReadGenericMethod;
1773 rows_per_strip=(uint32) image->rows;
1774 if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
1777 buffer[MagickPathExtent];
1779 method=ReadStripMethod;
1780 (void) FormatLocaleString(buffer,MagickPathExtent,"%u",
1781 (unsigned int) rows_per_strip);
1782 (void) SetImageProperty(image,"tiff:rows-per-strip",buffer,exception);
1784 if (rows_per_strip > (uint32) image->rows)
1785 rows_per_strip=(uint32) image->rows;
1786 if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
1787 if ((image->alpha_trait == UndefinedPixelTrait) ||
1788 (samples_per_pixel >= 4))
1789 method=ReadRGBAMethod;
1790 if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
1791 if ((image->alpha_trait == UndefinedPixelTrait) ||
1792 (samples_per_pixel >= 5))
1793 method=ReadCMYKAMethod;
1794 if ((photometric != PHOTOMETRIC_RGB) &&
1795 (photometric != PHOTOMETRIC_CIELAB) &&
1796 (photometric != PHOTOMETRIC_SEPARATED))
1797 method=ReadGenericMethod;
1798 if (image->storage_class == PseudoClass)
1799 method=ReadSingleSampleMethod;
1800 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1801 (photometric == PHOTOMETRIC_MINISWHITE))
1802 method=ReadSingleSampleMethod;
1803 if ((photometric != PHOTOMETRIC_SEPARATED) &&
1804 (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1805 method=ReadGenericMethod;
1806 if (image->compression == JPEGCompression)
1807 method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
1809 if (compress_tag == COMPRESSION_JBIG)
1810 method=ReadStripMethod;
1811 if (TIFFIsTiled(tiff) != MagickFalse)
1813 method=ReadRGBATileMethod;
1814 if (samples_per_pixel == 1)
1815 method=ReadTileMethod;
1817 quantum_info->endian=LSBEndian;
1818 quantum_type=RGBQuantum;
1819 if (TIFFScanlineSize(tiff) <= 0)
1820 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1821 if (((MagickSizeType) TIFFScanlineSize(tiff)) > (2*GetBlobSize(image)))
1822 ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile");
1823 number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t)
1824 image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/
1825 log(2.0))),image->columns*rows_per_strip));
1826 pixel_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));
1827 if (pixel_info == (MemoryInfo *) NULL)
1828 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1829 pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
1830 (void) memset(pixels,0,number_pixels*sizeof(uint32));
1833 case ReadSingleSampleMethod:
1836 Convert TIFF image to PseudoClass MIFF image.
1838 quantum_type=IndexQuantum;
1839 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
1840 if (image->alpha_trait != UndefinedPixelTrait)
1842 if (image->storage_class != PseudoClass)
1844 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1846 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
1850 quantum_type=IndexAlphaQuantum;
1851 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
1855 if (image->storage_class != PseudoClass)
1857 quantum_type=GrayQuantum;
1858 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
1860 status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
1861 bits_per_sample)/log(2))));
1862 if (status == MagickFalse)
1863 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1864 for (y=0; y < (ssize_t) image->rows; y++)
1869 tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);
1870 if (tiff_status == -1)
1872 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1873 if (q == (Quantum *) NULL)
1875 (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1876 quantum_type,pixels,exception);
1877 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1879 if (image->previous == (Image *) NULL)
1881 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1883 if (status == MagickFalse)
1889 case ReadRGBAMethod:
1892 Convert TIFF image to DirectClass MIFF image.
1894 pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1895 quantum_type=RGBQuantum;
1896 if (image->alpha_trait != UndefinedPixelTrait)
1898 quantum_type=RGBAQuantum;
1899 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1901 if (image->colorspace == CMYKColorspace)
1903 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1904 quantum_type=CMYKQuantum;
1905 if (image->alpha_trait != UndefinedPixelTrait)
1907 quantum_type=CMYKAQuantum;
1908 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1911 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1912 if (status == MagickFalse)
1913 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
1914 for (y=0; y < (ssize_t) image->rows; y++)
1919 tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);
1920 if (tiff_status == -1)
1922 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1923 if (q == (Quantum *) NULL)
1925 (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1926 quantum_type,pixels,exception);
1927 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1929 if (image->previous == (Image *) NULL)
1931 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1933 if (status == MagickFalse)
1939 case ReadCMYKAMethod:
1942 Convert TIFF image to DirectClass MIFF image.
1944 for (i=0; i < (ssize_t) samples_per_pixel; i++)
1946 for (y=0; y < (ssize_t) image->rows; y++)
1951 tiff_status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *)
1953 if (tiff_status == -1)
1955 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1956 if (q == (Quantum *) NULL)
1958 if (image->colorspace != CMYKColorspace)
1961 case 0: quantum_type=RedQuantum; break;
1962 case 1: quantum_type=GreenQuantum; break;
1963 case 2: quantum_type=BlueQuantum; break;
1964 case 3: quantum_type=AlphaQuantum; break;
1965 default: quantum_type=UndefinedQuantum; break;
1970 case 0: quantum_type=CyanQuantum; break;
1971 case 1: quantum_type=MagentaQuantum; break;
1972 case 2: quantum_type=YellowQuantum; break;
1973 case 3: quantum_type=BlackQuantum; break;
1974 case 4: quantum_type=AlphaQuantum; break;
1975 default: quantum_type=UndefinedQuantum; break;
1977 (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1978 quantum_type,pixels,exception);
1979 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1982 if (image->previous == (Image *) NULL)
1984 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1986 if (status == MagickFalse)
1992 case ReadYCCKMethod:
1994 for (y=0; y < (ssize_t) image->rows; y++)
2005 tiff_status=TIFFReadPixels(tiff,0,y,(char *) pixels);
2006 if (tiff_status == -1)
2008 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
2009 if (q == (Quantum *) NULL)
2012 for (x=0; x < (ssize_t) image->columns; x++)
2014 SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
2015 (1.402*(double) *(p+2))-179.456)),q);
2016 SetPixelMagenta(image,ScaleCharToQuantum(ClampYCC((double) *p-
2017 (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
2019 SetPixelYellow(image,ScaleCharToQuantum(ClampYCC((double) *p+
2020 (1.772*(double) *(p+1))-226.816)),q);
2021 SetPixelBlack(image,ScaleCharToQuantum((unsigned char) *(p+3)),q);
2022 q+=GetPixelChannels(image);
2025 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2027 if (image->previous == (Image *) NULL)
2029 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2031 if (status == MagickFalse)
2037 case ReadStripMethod:
2043 Convert stripped TIFF image to DirectClass MIFF image.
2045 (void) SetImageStorageClass(image,DirectClass,exception);
2048 for (y=0; y < (ssize_t) image->rows; y++)
2056 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
2057 if (q == (Quantum *) NULL)
2061 if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
2063 i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
2067 p=((uint32 *) pixels)+image->columns*i;
2068 for (x=0; x < (ssize_t) image->columns; x++)
2070 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
2072 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
2074 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
2076 if (image->alpha_trait != UndefinedPixelTrait)
2077 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
2080 q+=GetPixelChannels(image);
2082 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2084 if (image->previous == (Image *) NULL)
2086 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2088 if (status == MagickFalse)
2094 case ReadTileMethod:
2096 register unsigned char
2107 Convert tiled TIFF image to DirectClass MIFF image.
2109 quantum_type=IndexQuantum;
2110 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
2111 if (image->alpha_trait != UndefinedPixelTrait)
2113 if (image->storage_class != PseudoClass)
2115 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
2117 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
2121 quantum_type=IndexAlphaQuantum;
2122 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
2126 if (image->storage_class != PseudoClass)
2128 quantum_type=GrayQuantum;
2129 pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
2131 status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
2132 bits_per_sample)/log(2))));
2133 if (status == MagickFalse)
2134 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2135 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
2136 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
2137 ThrowTIFFException(CoderError,"ImageIsNotTiled");
2138 if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||
2139 (AcquireMagickResource(HeightResource,rows) == MagickFalse))
2140 ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit");
2141 (void) SetImageStorageClass(image,DirectClass,exception);
2142 number_pixels=(MagickSizeType) columns*rows;
2143 if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
2144 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2145 tile_pixels=(unsigned char *) AcquireQuantumMemory(TIFFTileSize(tiff)+
2146 sizeof(uint32),sizeof(*tile_pixels));
2147 if (tile_pixels == (unsigned char *) NULL)
2148 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2149 (void) memset(tile_pixels,0,TIFFTileSize(tiff)*sizeof(*tile_pixels));
2150 for (y=0; y < (ssize_t) image->rows; y+=rows)
2158 rows_remaining=image->rows-y;
2159 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
2160 rows_remaining=rows;
2161 for (x=0; x < (ssize_t) image->columns; x+=columns)
2167 columns_remaining=image->columns-x;
2168 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
2169 columns_remaining=columns;
2170 if (TIFFReadTile(tiff,tile_pixels,(uint32) x,(uint32) y,0,0) == 0)
2173 for (row=0; row < rows_remaining; row++)
2178 q=GetAuthenticPixels(image,x,y+row,columns_remaining,1,exception);
2179 if (q == (Quantum *) NULL)
2181 (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
2182 quantum_type,p,exception);
2183 p+=TIFFTileRowSize(tiff);
2184 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2188 if (image->previous == (Image *) NULL)
2190 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2192 if (status == MagickFalse)
2196 tile_pixels=(unsigned char *) RelinquishMagickMemory(tile_pixels);
2199 case ReadRGBATileMethod:
2210 Convert tiled TIFF image to DirectClass MIFF image.
2212 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
2213 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
2214 ThrowTIFFException(CoderError,"ImageIsNotTiled");
2215 if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||
2216 (AcquireMagickResource(HeightResource,rows) == MagickFalse))
2217 ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit");
2218 (void) SetImageStorageClass(image,DirectClass,exception);
2219 number_pixels=(MagickSizeType) columns*rows;
2220 if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
2221 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2222 tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
2223 sizeof(*tile_pixels));
2224 if (tile_pixels == (uint32 *) NULL)
2225 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2226 for (y=0; y < (ssize_t) image->rows; y+=rows)
2233 *magick_restrict tile;
2239 rows_remaining=image->rows-y;
2240 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
2241 rows_remaining=rows;
2242 tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
2244 if (tile == (Quantum *) NULL)
2246 for (x=0; x < (ssize_t) image->columns; x+=columns)
2252 if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
2254 columns_remaining=image->columns-x;
2255 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
2256 columns_remaining=columns;
2257 p=tile_pixels+(rows-rows_remaining)*columns;
2258 q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
2260 for (row=rows_remaining; row > 0; row--)
2262 if (image->alpha_trait != UndefinedPixelTrait)
2263 for (column=columns_remaining; column > 0; column--)
2265 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
2267 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
2269 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
2271 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
2274 q+=GetPixelChannels(image);
2277 for (column=columns_remaining; column > 0; column--)
2279 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
2281 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
2283 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
2286 q+=GetPixelChannels(image);
2288 p+=columns-columns_remaining;
2289 q-=GetPixelChannels(image)*(image->columns+columns_remaining);
2292 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2294 if (image->previous == (Image *) NULL)
2296 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2298 if (status == MagickFalse)
2302 tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
2305 case ReadGenericMethod:
2309 *generic_info = (MemoryInfo * ) NULL;
2318 Convert TIFF image to DirectClass MIFF image.
2320 (void) SetImageStorageClass(image,DirectClass,exception);
2321 if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
2322 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2323 number_pixels=(MagickSizeType) image->columns*image->rows;
2324 generic_info=AcquireVirtualMemory(number_pixels,sizeof(uint32));
2325 if (generic_info == (MemoryInfo *) NULL)
2326 ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
2327 pixels=(uint32 *) GetVirtualMemoryBlob(generic_info);
2328 (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
2329 image->rows,(uint32 *) pixels,0);
2331 Convert image to DirectClass pixel packets.
2333 p=pixels+number_pixels-1;
2334 for (y=0; y < (ssize_t) image->rows; y++)
2342 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
2343 if (q == (Quantum *) NULL)
2345 q+=GetPixelChannels(image)*(image->columns-1);
2346 for (x=0; x < (ssize_t) image->columns; x++)
2348 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
2350 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
2352 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
2354 if (image->alpha_trait != UndefinedPixelTrait)
2355 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
2358 q-=GetPixelChannels(image);
2360 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2362 if (image->previous == (Image *) NULL)
2364 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
2366 if (status == MagickFalse)
2370 generic_info=RelinquishVirtualMemory(generic_info);
2374 pixel_info=RelinquishVirtualMemory(pixel_info);
2375 SetQuantumImageType(image,quantum_type);
2377 if (quantum_info != (QuantumInfo *) NULL)
2378 quantum_info=DestroyQuantumInfo(quantum_info);
2379 if (photometric == PHOTOMETRIC_CIELAB)
2380 DecodeLabImage(image,exception);
2381 if ((photometric == PHOTOMETRIC_LOGL) ||
2382 (photometric == PHOTOMETRIC_MINISBLACK) ||
2383 (photometric == PHOTOMETRIC_MINISWHITE))
2385 image->type=GrayscaleType;
2386 if (bits_per_sample == 1)
2387 image->type=BilevelType;
2390 Proceed to next image.
2392 if (image_info->number_scenes != 0)
2393 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
2395 more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
2396 if (more_frames != MagickFalse)
2399 Allocate next image structure.
2401 AcquireNextImage(image_info,image,exception);
2402 if (GetNextImageInList(image) == (Image *) NULL)
2407 image=SyncNextImageInList(image);
2408 status=SetImageProgress(image,LoadImagesTag,image->scene-1,
2410 if (status == MagickFalse)
2413 } while ((status != MagickFalse) && (more_frames != MagickFalse));
2415 TIFFReadPhotoshopLayers(image_info,image,exception);
2416 if ((image_info->number_scenes != 0) &&
2417 (image_info->scene >= GetImageListLength(image)))
2419 if (status == MagickFalse)
2420 return(DestroyImageList(image));
2421 return(GetFirstImageInList(image));
2426 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2430 % R e g i s t e r T I F F I m a g e %
2434 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2436 % RegisterTIFFImage() adds properties for the TIFF image format to
2437 % the list of supported formats. The properties include the image format
2438 % tag, a method to read and/or write the format, whether the format
2439 % supports the saving of more than one frame to the same file or blob,
2440 % whether the format supports native in-memory I/O, and a brief
2441 % description of the format.
2443 % The format of the RegisterTIFFImage method is:
2445 % size_t RegisterTIFFImage(void)
2449 #if defined(MAGICKCORE_TIFF_DELEGATE)
2450 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2451 static TIFFExtendProc
2452 tag_extender = (TIFFExtendProc) NULL;
2454 static void TIFFIgnoreTags(TIFF *tiff)
2475 if (TIFFGetReadProc(tiff) != TIFFReadBlob)
2477 image=(Image *)TIFFClientdata(tiff);
2478 tags=GetImageArtifact(image,"tiff:ignore-tags");
2479 if (tags == (const char *) NULL)
2485 while ((isspace((int) ((unsigned char) *p)) != 0))
2488 (void) strtol(p,&q,10);
2495 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
2502 ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
2503 if (ignore == (TIFFFieldInfo *) NULL)
2506 This also sets field_bit to 0 (FIELD_IGNORE).
2508 (void) memset(ignore,0,count*sizeof(*ignore));
2511 while ((isspace((int) ((unsigned char) *p)) != 0))
2514 ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
2519 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
2522 (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
2523 ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
2526 static void TIFFTagExtender(TIFF *tiff)
2528 static const TIFFFieldInfo
2531 { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
2532 (char *) "PhotoshopLayerData" },
2533 { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
2534 (char *) "Microscope" }
2537 TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
2538 sizeof(*TIFFExtensions));
2539 if (tag_extender != (TIFFExtendProc) NULL)
2540 (*tag_extender)(tiff);
2541 TIFFIgnoreTags(tiff);
2546 ModuleExport size_t RegisterTIFFImage(void)
2548 #define TIFFDescription "Tagged Image File Format"
2551 version[MagickPathExtent];
2556 #if defined(MAGICKCORE_TIFF_DELEGATE)
2557 if (tiff_semaphore == (SemaphoreInfo *) NULL)
2558 ActivateSemaphoreInfo(&tiff_semaphore);
2559 LockSemaphoreInfo(tiff_semaphore);
2560 if (instantiate_key == MagickFalse)
2562 if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
2563 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2564 error_handler=TIFFSetErrorHandler(TIFFErrors);
2565 warning_handler=TIFFSetWarningHandler(TIFFWarnings);
2566 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2567 if (tag_extender == (TIFFExtendProc) NULL)
2568 tag_extender=TIFFSetTagExtender(TIFFTagExtender);
2570 instantiate_key=MagickTrue;
2572 UnlockSemaphoreInfo(tiff_semaphore);
2575 #if defined(TIFF_VERSION)
2576 (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION);
2578 #if defined(MAGICKCORE_TIFF_DELEGATE)
2587 for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++)
2593 entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4");
2594 #if defined(MAGICKCORE_TIFF_DELEGATE)
2595 entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
2596 entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
2598 entry->flags|=CoderRawSupportFlag;
2599 entry->flags|=CoderEndianSupportFlag;
2600 entry->flags|=CoderDecoderSeekableStreamFlag;
2601 entry->flags|=CoderEncoderSeekableStreamFlag;
2602 entry->flags^=CoderAdjoinFlag;
2603 entry->flags^=CoderUseExtensionFlag;
2604 entry->format_type=ImplicitFormatType;
2605 entry->mime_type=ConstantString("image/tiff");
2606 (void) RegisterMagickInfo(entry);
2607 entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF");
2608 #if defined(MAGICKCORE_TIFF_DELEGATE)
2609 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2610 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
2612 entry->flags|=CoderEndianSupportFlag;
2613 entry->flags|=CoderDecoderSeekableStreamFlag;
2614 entry->flags|=CoderEncoderSeekableStreamFlag;
2615 entry->flags^=CoderUseExtensionFlag;
2616 entry->mime_type=ConstantString("image/tiff");
2617 (void) RegisterMagickInfo(entry);
2618 entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription);
2619 #if defined(MAGICKCORE_TIFF_DELEGATE)
2620 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2621 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2623 entry->flags|=CoderEndianSupportFlag;
2624 entry->flags|=CoderDecoderSeekableStreamFlag;
2625 entry->flags|=CoderEncoderSeekableStreamFlag;
2626 entry->flags|=CoderStealthFlag;
2627 entry->flags^=CoderUseExtensionFlag;
2628 if (*version != '\0')
2629 entry->version=ConstantString(version);
2630 entry->mime_type=ConstantString("image/tiff");
2631 (void) RegisterMagickInfo(entry);
2632 entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription);
2633 #if defined(MAGICKCORE_TIFF_DELEGATE)
2634 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2635 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2637 entry->magick=(IsImageFormatHandler *) IsTIFF;
2638 entry->flags|=CoderEndianSupportFlag;
2639 entry->flags|=CoderDecoderSeekableStreamFlag;
2640 entry->flags|=CoderEncoderSeekableStreamFlag;
2641 entry->flags^=CoderUseExtensionFlag;
2642 if (*version != '\0')
2643 entry->version=ConstantString(version);
2644 entry->mime_type=ConstantString("image/tiff");
2645 (void) RegisterMagickInfo(entry);
2646 entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)");
2647 #if defined(TIFF_VERSION_BIG)
2648 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2649 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2651 entry->flags|=CoderEndianSupportFlag;
2652 entry->flags|=CoderDecoderSeekableStreamFlag;
2653 entry->flags|=CoderEncoderSeekableStreamFlag;
2654 entry->flags^=CoderUseExtensionFlag;
2655 if (*version != '\0')
2656 entry->version=ConstantString(version);
2657 entry->mime_type=ConstantString("image/tiff");
2658 (void) RegisterMagickInfo(entry);
2659 return(MagickImageCoderSignature);
2663 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2667 % U n r e g i s t e r T I F F I m a g e %
2671 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2673 % UnregisterTIFFImage() removes format registrations made by the TIFF module
2674 % from the list of supported formats.
2676 % The format of the UnregisterTIFFImage method is:
2678 % UnregisterTIFFImage(void)
2681 ModuleExport void UnregisterTIFFImage(void)
2683 (void) UnregisterMagickInfo("TIFF64");
2684 (void) UnregisterMagickInfo("TIFF");
2685 (void) UnregisterMagickInfo("TIF");
2686 (void) UnregisterMagickInfo("PTIF");
2687 #if defined(MAGICKCORE_TIFF_DELEGATE)
2688 if (tiff_semaphore == (SemaphoreInfo *) NULL)
2689 ActivateSemaphoreInfo(&tiff_semaphore);
2690 LockSemaphoreInfo(tiff_semaphore);
2691 if (instantiate_key != MagickFalse)
2693 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2694 if (tag_extender == (TIFFExtendProc) NULL)
2695 (void) TIFFSetTagExtender(tag_extender);
2697 if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
2698 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2699 (void) TIFFSetWarningHandler(warning_handler);
2700 (void) TIFFSetErrorHandler(error_handler);
2701 instantiate_key=MagickFalse;
2703 UnlockSemaphoreInfo(tiff_semaphore);
2704 RelinquishSemaphoreInfo(&tiff_semaphore);
2708 #if defined(MAGICKCORE_TIFF_DELEGATE)
2710 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2714 % W r i t e G R O U P 4 I m a g e %
2718 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2720 % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
2722 % The format of the WriteGROUP4Image method is:
2724 % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2725 % Image *image,ExceptionInfo *)
2727 % A description of each parameter follows:
2729 % o image_info: the image info.
2731 % o image: The image.
2733 % o exception: return any errors or warnings in this structure.
2736 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2737 Image *image,ExceptionInfo *exception)
2740 filename[MagickPathExtent];
2774 Write image as CCITT Group4 TIFF image to a temporary file.
2776 assert(image_info != (const ImageInfo *) NULL);
2777 assert(image_info->signature == MagickCoreSignature);
2778 assert(image != (Image *) NULL);
2779 assert(image->signature == MagickCoreSignature);
2780 if (image->debug != MagickFalse)
2781 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2782 assert(exception != (ExceptionInfo *) NULL);
2783 assert(exception->signature == MagickCoreSignature);
2784 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2785 if (status == MagickFalse)
2787 huffman_image=CloneImage(image,0,0,MagickTrue,exception);
2788 if (huffman_image == (Image *) NULL)
2790 (void) CloseBlob(image);
2791 return(MagickFalse);
2793 huffman_image->endian=MSBEndian;
2795 unique_file=AcquireUniqueFileResource(filename);
2796 if (unique_file != -1)
2797 file=fdopen(unique_file,"wb");
2798 if ((unique_file == -1) || (file == (FILE *) NULL))
2800 ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
2802 return(MagickFalse);
2804 (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s",
2806 (void) SetImageType(huffman_image,BilevelType,exception);
2807 write_info=CloneImageInfo((ImageInfo *) NULL);
2808 SetImageInfoFile(write_info,file);
2809 (void) SetImageDepth(image,1,exception);
2810 (void) SetImageType(image,BilevelType,exception);
2811 write_info->compression=Group4Compression;
2812 write_info->type=BilevelType;
2813 status=WriteTIFFImage(write_info,huffman_image,exception);
2814 (void) fflush(file);
2815 write_info=DestroyImageInfo(write_info);
2816 if (status == MagickFalse)
2818 huffman_image=DestroyImage(huffman_image);
2819 (void) fclose(file);
2820 (void) RelinquishUniqueFileResource(filename);
2821 return(MagickFalse);
2823 tiff=TIFFOpen(filename,"rb");
2824 if (tiff == (TIFF *) NULL)
2826 huffman_image=DestroyImage(huffman_image);
2827 (void) fclose(file);
2828 (void) RelinquishUniqueFileResource(filename);
2829 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
2830 image_info->filename);
2831 return(MagickFalse);
2834 Allocate raw strip buffer.
2836 if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2839 huffman_image=DestroyImage(huffman_image);
2840 (void) fclose(file);
2841 (void) RelinquishUniqueFileResource(filename);
2842 return(MagickFalse);
2844 strip_size=byte_count[0];
2845 for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2846 if (byte_count[i] > strip_size)
2847 strip_size=byte_count[i];
2848 buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2850 if (buffer == (unsigned char *) NULL)
2853 huffman_image=DestroyImage(huffman_image);
2854 (void) fclose(file);
2855 (void) RelinquishUniqueFileResource(filename);
2856 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2857 image_info->filename);
2860 Compress runlength encoded to 2D Huffman pixels.
2862 for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2864 count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2865 if (WriteBlob(image,(size_t) count,buffer) != count)
2868 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2870 huffman_image=DestroyImage(huffman_image);
2871 (void) fclose(file);
2872 (void) RelinquishUniqueFileResource(filename);
2873 (void) CloseBlob(image);
2878 #if defined(MAGICKCORE_TIFF_DELEGATE)
2880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2884 % W r i t e P T I F I m a g e %
2888 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2890 % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2893 % The format of the WritePTIFImage method is:
2895 % MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2896 % Image *image,ExceptionInfo *exception)
2898 % A description of each parameter follows:
2900 % o image_info: the image info.
2902 % o image: The image.
2904 % o exception: return any errors or warnings in this structure.
2907 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2908 Image *image,ExceptionInfo *exception)
2929 Create pyramid-encoded TIFF image.
2931 images=NewImageList();
2932 for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2937 clone_image=CloneImage(next,0,0,MagickFalse,exception);
2938 if (clone_image == (Image *) NULL)
2940 clone_image->previous=NewImageList();
2941 clone_image->next=NewImageList();
2942 (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
2943 AppendImageToList(&images,clone_image);
2944 columns=next->columns;
2946 resolution=next->resolution;
2947 while ((columns > 64) && (rows > 64))
2953 pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
2954 if (pyramid_image == (Image *) NULL)
2956 DestroyBlob(pyramid_image);
2957 pyramid_image->blob=ReferenceBlob(next->blob);
2958 pyramid_image->resolution=resolution;
2959 (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
2961 AppendImageToList(&images,pyramid_image);
2965 if (images != (Image *) NULL)
2968 Write pyramid-encoded TIFF image.
2970 images=GetFirstImageInList(images);
2971 write_info=CloneImageInfo(image_info);
2972 write_info->adjoin=MagickTrue;
2973 (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
2974 (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
2975 status=WriteTIFFImage(write_info,images,exception);
2976 images=DestroyImageList(images);
2977 write_info=DestroyImageInfo(write_info);
2983 #if defined(MAGICKCORE_TIFF_DELEGATE)
2985 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2988 % W r i t e T I F F I m a g e %
2992 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2994 % WriteTIFFImage() writes an image in the Tagged image file format.
2996 % The format of the WriteTIFFImage method is:
2998 % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2999 % Image *image,ExceptionInfo *exception)
3001 % A description of each parameter follows:
3003 % o image_info: the image info.
3005 % o image: The image.
3007 % o exception: return any errors or warnings in this structure.
3011 typedef struct _TIFFInfo
3022 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
3024 assert(tiff_info != (TIFFInfo *) NULL);
3025 if (tiff_info->scanlines != (unsigned char *) NULL)
3026 tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
3027 tiff_info->scanlines);
3028 if (tiff_info->pixels != (unsigned char *) NULL)
3029 tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
3033 static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
3045 image_view=AcquireAuthenticCacheView(image,exception);
3046 for (y=0; y < (ssize_t) image->rows; y++)
3054 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3055 if (q == (Quantum *) NULL)
3060 for (x=0; x < (ssize_t) image->columns; x++)
3066 a=QuantumScale*GetPixela(image,q)-0.5;
3069 b=QuantumScale*GetPixelb(image,q)-0.5;
3072 SetPixela(image,QuantumRange*a,q);
3073 SetPixelb(image,QuantumRange*b,q);
3074 q+=GetPixelChannels(image);
3076 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3082 image_view=DestroyCacheView(image_view);
3086 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
3087 TIFF *tiff,TIFFInfo *tiff_info)
3099 assert(tiff_info != (TIFFInfo *) NULL);
3100 (void) memset(tiff_info,0,sizeof(*tiff_info));
3101 option=GetImageOption(image_info,"tiff:tile-geometry");
3102 if (option == (const char *) NULL)
3107 rows_per_strip=0; /* use default */
3108 option=GetImageOption(image_info,"tiff:rows-per-strip");
3109 if (option != (const char *) NULL)
3110 rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
3112 if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0)
3114 rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip);
3115 (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
3119 Create tiled TIFF, ignore "tiff:rows-per-strip".
3121 flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
3122 if ((flags & HeightValue) == 0)
3123 tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
3124 tile_columns=(uint32) tiff_info->tile_geometry.width;
3125 tile_rows=(uint32) tiff_info->tile_geometry.height;
3126 TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
3127 (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
3128 (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
3129 tiff_info->tile_geometry.width=tile_columns;
3130 tiff_info->tile_geometry.height=tile_rows;
3131 if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0))
3133 DestroyTIFFInfo(tiff_info);
3134 return(MagickFalse);
3136 tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
3137 tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
3138 tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
3139 tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
3140 if ((tiff_info->scanlines == (unsigned char *) NULL) ||
3141 (tiff_info->pixels == (unsigned char *) NULL))
3143 DestroyTIFFInfo(tiff_info);
3144 return(MagickFalse);
3149 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
3150 tsample_t sample,Image *image)
3158 register unsigned char
3172 if (TIFFIsTiled(tiff) == 0)
3173 return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
3175 Fill scanlines to tile height.
3177 i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
3178 (void) memcpy(tiff_info->scanlines+i,(char *) tiff_info->scanline,
3179 (size_t) TIFFScanlineSize(tiff));
3180 if (((size_t) (row % tiff_info->tile_geometry.height) !=
3181 (tiff_info->tile_geometry.height-1)) &&
3182 (row != (ssize_t) (image->rows-1)))
3185 Write tile to TIFF image.
3188 bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
3189 tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
3190 number_tiles=(image->columns+tiff_info->tile_geometry.width)/
3191 tiff_info->tile_geometry.width;
3192 for (i=0; i < (ssize_t) number_tiles; i++)
3194 tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
3195 tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
3196 for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
3197 for (k=0; k < (ssize_t) tile_width; k++)
3199 if (bytes_per_pixel == 0)
3201 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
3202 tiff_info->tile_geometry.width+k)/8);
3203 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
3207 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
3208 tiff_info->tile_geometry.width+k)*bytes_per_pixel);
3209 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
3210 for (l=0; l < bytes_per_pixel; l++)
3213 if ((i*tiff_info->tile_geometry.width) != image->columns)
3214 status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
3215 tiff_info->tile_geometry.width),(uint32) ((row/
3216 tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
3224 static ssize_t TIFFWriteCustomStream(unsigned char *data,const size_t count,
3232 profile=(PhotoshopProfile *) user_data;
3233 if ((profile->offset+(MagickOffsetType) count) >=
3234 (MagickOffsetType) profile->extent)
3236 profile->extent+=count+profile->quantum;
3237 profile->quantum<<=1;
3238 SetStringInfoLength(profile->data,profile->extent);
3240 (void) memcpy(profile->data->datum+profile->offset,data,count);
3241 profile->offset+=count;
3245 static CustomStreamInfo *TIFFAcquireCustomStreamForWriting(
3246 PhotoshopProfile *profile,ExceptionInfo *exception)
3251 custom_stream=AcquireCustomStreamInfo(exception);
3252 if (custom_stream == (CustomStreamInfo *) NULL)
3253 return(custom_stream);
3254 SetCustomStreamData(custom_stream,(void *) profile);
3255 SetCustomStreamWriter(custom_stream,TIFFWriteCustomStream);
3256 SetCustomStreamSeeker(custom_stream,TIFFSeekCustomStream);
3257 SetCustomStreamTeller(custom_stream,TIFFTellCustomStream);
3258 return(custom_stream);
3261 static MagickBooleanType TIFFWritePhotoshopLayers(Image* image,
3262 const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception)
3289 base_image=CloneImage(image,0,0,MagickFalse,exception);
3290 if (base_image == (Image *) NULL)
3292 clone_info=CloneImageInfo(image_info);
3293 if (clone_info == (ImageInfo *) NULL)
3294 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3297 profile.quantum=MagickMinBlobExtent;
3298 layers=AcquireStringInfo(profile.quantum);
3299 if (layers == (StringInfo *) NULL)
3301 base_image=DestroyImage(base_image);
3302 clone_info=DestroyImageInfo(clone_info);
3303 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3306 profile.data=layers;
3307 profile.extent=layers->length;
3308 custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception);
3309 if (custom_stream == (CustomStreamInfo *) NULL)
3311 base_image=DestroyImage(base_image);
3312 clone_info=DestroyImageInfo(clone_info);
3313 layers=DestroyStringInfo(layers);
3314 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3317 blob=CloneBlobInfo((BlobInfo *) NULL);
3318 if (blob == (BlobInfo *) NULL)
3320 base_image=DestroyImage(base_image);
3321 clone_info=DestroyImageInfo(clone_info);
3322 layers=DestroyStringInfo(layers);
3323 custom_stream=DestroyCustomStreamInfo(custom_stream);
3324 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3327 DestroyBlob(base_image);
3328 base_image->blob=blob;
3330 while (next != (Image *) NULL)
3331 next=SyncNextImageInList(next);
3332 AttachCustomStream(base_image->blob,custom_stream);
3333 InitPSDInfo(image,&info);
3334 base_image->endian=endian;
3335 WriteBlobString(base_image,"Adobe Photoshop Document Data Block");
3336 WriteBlobByte(base_image,0);
3337 WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" :
3339 status=WritePSDLayers(base_image,clone_info,&info,exception);
3340 if (status != MagickFalse)
3342 SetStringInfoLength(layers,(size_t) profile.offset);
3343 status=SetImageProfile(image,"tiff:37724",layers,exception);
3346 while (next != (Image *) NULL)
3351 layers=DestroyStringInfo(layers);
3352 clone_info=DestroyImageInfo(clone_info);
3353 custom_stream=DestroyCustomStreamInfo(custom_stream);
3357 static void TIFFSetProfiles(TIFF *tiff,Image *image)
3365 if (image->profiles == (void *) NULL)
3367 ResetImageProfileIterator(image);
3368 for (name=GetNextImageProfile(image); name != (const char *) NULL; )
3370 profile=GetImageProfile(image,name);
3371 if (GetStringInfoLength(profile) == 0)
3373 name=GetNextImageProfile(image);
3376 #if defined(TIFFTAG_XMLPACKET)
3377 if (LocaleCompare(name,"xmp") == 0)
3378 (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
3379 profile),GetStringInfoDatum(profile));
3381 #if defined(TIFFTAG_ICCPROFILE)
3382 if (LocaleCompare(name,"icc") == 0)
3383 (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
3384 profile),GetStringInfoDatum(profile));
3386 if (LocaleCompare(name,"iptc") == 0)
3394 iptc_profile=CloneStringInfo(profile);
3395 length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
3397 SetStringInfoLength(iptc_profile,length);
3398 if (TIFFIsByteSwapped(tiff))
3399 TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
3400 (unsigned long) (length/4));
3401 (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
3402 GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
3403 iptc_profile=DestroyStringInfo(iptc_profile);
3405 #if defined(TIFFTAG_PHOTOSHOP)
3406 if (LocaleCompare(name,"8bim") == 0)
3407 (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
3408 GetStringInfoLength(profile),GetStringInfoDatum(profile));
3410 if (LocaleCompare(name,"tiff:37724") == 0)
3411 (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
3412 GetStringInfoDatum(profile));
3413 if (LocaleCompare(name,"tiff:34118") == 0)
3414 (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
3415 GetStringInfoDatum(profile));
3416 name=GetNextImageProfile(image);
3420 static void TIFFSetProperties(TIFF *tiff,const MagickBooleanType adjoin,
3421 Image *image,ExceptionInfo *exception)
3426 value=GetImageArtifact(image,"tiff:document");
3427 if (value != (const char *) NULL)
3428 (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
3429 value=GetImageArtifact(image,"tiff:hostcomputer");
3430 if (value != (const char *) NULL)
3431 (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
3432 value=GetImageArtifact(image,"tiff:artist");
3433 if (value != (const char *) NULL)
3434 (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
3435 value=GetImageArtifact(image,"tiff:timestamp");
3436 if (value != (const char *) NULL)
3437 (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
3438 value=GetImageArtifact(image,"tiff:make");
3439 if (value != (const char *) NULL)
3440 (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
3441 value=GetImageArtifact(image,"tiff:model");
3442 if (value != (const char *) NULL)
3443 (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
3444 value=GetImageArtifact(image,"tiff:software");
3445 if (value != (const char *) NULL)
3446 (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
3447 value=GetImageArtifact(image,"tiff:copyright");
3448 if (value != (const char *) NULL)
3449 (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
3450 value=GetImageArtifact(image,"kodak-33423");
3451 if (value != (const char *) NULL)
3452 (void) TIFFSetField(tiff,33423,value);
3453 value=GetImageArtifact(image,"kodak-36867");
3454 if (value != (const char *) NULL)
3455 (void) TIFFSetField(tiff,36867,value);
3456 value=GetImageProperty(image,"label",exception);
3457 if (value != (const char *) NULL)
3458 (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
3459 value=GetImageProperty(image,"comment",exception);
3460 if (value != (const char *) NULL)
3461 (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
3462 value=GetImageArtifact(image,"tiff:subfiletype");
3463 if (value != (const char *) NULL)
3465 if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
3466 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
3468 if (LocaleCompare(value,"PAGE") == 0)
3469 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3471 if (LocaleCompare(value,"MASK") == 0)
3472 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
3480 page=(uint16) image->scene;
3481 pages=(uint16) GetImageListLength(image);
3482 if ((adjoin != MagickFalse) && (pages > 1))
3483 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3484 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3488 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
3489 ExceptionInfo *exception)
3491 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
3502 Write EXIF properties.
3505 (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
3506 for (i=0; exif_info[i].tag != 0; i++)
3508 value=GetImageProperty(image,exif_info[i].property,exception);
3509 if (value == (const char *) NULL)
3511 switch (exif_info[i].type)
3515 (void) TIFFSetField(tiff,exif_info[i].tag,value);
3523 field=(uint16) StringToLong(value);
3524 (void) TIFFSetField(tiff,exif_info[i].tag,field);
3532 field=(uint16) StringToLong(value);
3533 (void) TIFFSetField(tiff,exif_info[i].tag,field);
3537 case TIFF_SRATIONAL:
3542 field=StringToDouble(value,(char **) NULL);
3543 (void) TIFFSetField(tiff,exif_info[i].tag,field);
3550 /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
3557 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
3558 Image *image,ExceptionInfo *exception)
3613 assert(image_info != (const ImageInfo *) NULL);
3614 assert(image_info->signature == MagickCoreSignature);
3615 assert(image != (Image *) NULL);
3616 assert(image->signature == MagickCoreSignature);
3617 if (image->debug != MagickFalse)
3618 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3619 assert(exception != (ExceptionInfo *) NULL);
3620 assert(exception->signature == MagickCoreSignature);
3621 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
3622 if (status == MagickFalse)
3624 (void) SetMagickThreadValue(tiff_exception,exception);
3625 endian_type=(HOST_FILLORDER == FILLORDER_LSB2MSB) ? LSBEndian : MSBEndian;
3626 option=GetImageOption(image_info,"tiff:endian");
3627 if (option != (const char *) NULL)
3629 if (LocaleNCompare(option,"msb",3) == 0)
3630 endian_type=MSBEndian;
3631 if (LocaleNCompare(option,"lsb",3) == 0)
3632 endian_type=LSBEndian;
3634 mode=endian_type == LSBEndian ? "wl" : "wb";
3635 #if defined(TIFF_VERSION_BIG)
3636 if ((LocaleCompare(image_info->magick,"TIFF64") == 0) ||
3637 (((MagickOffsetType) image->columns*image->rows) > SSIZE_MAX))
3638 mode=endian_type == LSBEndian ? "wl8" : "wb8";
3640 tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
3641 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
3643 if (tiff == (TIFF *) NULL)
3644 return(MagickFalse);
3645 if (exception->severity > ErrorException)
3648 return(MagickFalse);
3650 (void) DeleteImageProfile(image,"tiff:37724");
3652 debug=IsEventLogging();
3654 adjoin=image_info->adjoin;
3655 imageListLength=GetImageListLength(image);
3659 Initialize TIFF fields.
3661 if ((image_info->type != UndefinedType) &&
3662 (image_info->type != OptimizeType))
3663 (void) SetImageType(image,image_info->type,exception);
3664 compression=UndefinedCompression;
3665 if (image->compression != JPEGCompression)
3666 compression=image->compression;
3667 if (image_info->compression != UndefinedCompression)
3668 compression=image_info->compression;
3669 switch (compression)
3671 case FaxCompression:
3672 case Group4Compression:
3674 (void) SetImageType(image,BilevelType,exception);
3675 (void) SetImageDepth(image,1,exception);
3678 case JPEGCompression:
3680 (void) SetImageStorageClass(image,DirectClass,exception);
3681 (void) SetImageDepth(image,8,exception);
3687 quantum_info=AcquireQuantumInfo(image_info,image);
3688 if (quantum_info == (QuantumInfo *) NULL)
3689 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3690 if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
3691 (quantum_info->format == UndefinedQuantumFormat) &&
3692 (IsHighDynamicRangeImage(image,exception) != MagickFalse))
3694 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
3695 if (status == MagickFalse)
3697 quantum_info=DestroyQuantumInfo(quantum_info);
3698 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3701 if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
3702 (GetPreviousImageInList(image) != (Image *) NULL))
3703 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
3704 if ((image->columns != (uint32) image->columns) ||
3705 (image->rows != (uint32) image->rows))
3706 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
3707 (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
3708 (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
3709 switch (compression)
3711 case FaxCompression:
3713 compress_tag=COMPRESSION_CCITTFAX3;
3714 option=GetImageOption(image_info,"quantum:polarity");
3715 if (option == (const char *) NULL)
3716 SetQuantumMinIsWhite(quantum_info,MagickTrue);
3719 case Group4Compression:
3721 compress_tag=COMPRESSION_CCITTFAX4;
3722 option=GetImageOption(image_info,"quantum:polarity");
3723 if (option == (const char *) NULL)
3724 SetQuantumMinIsWhite(quantum_info,MagickTrue);
3727 #if defined(COMPRESSION_JBIG)
3728 case JBIG1Compression:
3730 compress_tag=COMPRESSION_JBIG;
3734 case JPEGCompression:
3736 compress_tag=COMPRESSION_JPEG;
3739 #if defined(COMPRESSION_LZMA)
3740 case LZMACompression:
3742 compress_tag=COMPRESSION_LZMA;
3746 case LZWCompression:
3748 compress_tag=COMPRESSION_LZW;
3751 case RLECompression:
3753 compress_tag=COMPRESSION_PACKBITS;
3756 case ZipCompression:
3758 compress_tag=COMPRESSION_ADOBE_DEFLATE;
3761 #if defined(COMPRESSION_ZSTD)
3762 case ZstdCompression:
3764 compress_tag=COMPRESSION_ZSTD;
3771 compress_tag=COMPRESSION_NONE;
3775 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
3776 if ((compress_tag != COMPRESSION_NONE) &&
3777 (TIFFIsCODECConfigured(compress_tag) == 0))
3779 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3780 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
3781 MagickCompressOptions,(ssize_t) compression));
3782 compress_tag=COMPRESSION_NONE;
3783 compression=NoCompression;
3786 switch (compress_tag)
3788 #if defined(CCITT_SUPPORT)
3789 case COMPRESSION_CCITTFAX3:
3790 case COMPRESSION_CCITTFAX4:
3792 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
3793 case COMPRESSION_JPEG:
3795 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3796 case COMPRESSION_LZMA:
3798 #if defined(LZW_SUPPORT)
3799 case COMPRESSION_LZW:
3801 #if defined(PACKBITS_SUPPORT)
3802 case COMPRESSION_PACKBITS:
3804 #if defined(ZIP_SUPPORT)
3805 case COMPRESSION_ADOBE_DEFLATE:
3807 case COMPRESSION_NONE:
3811 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3812 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
3813 MagickCompressOptions,(ssize_t) compression));
3814 compress_tag=COMPRESSION_NONE;
3815 compression=NoCompression;
3820 if (image->colorspace == CMYKColorspace)
3822 photometric=PHOTOMETRIC_SEPARATED;
3823 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
3824 (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
3829 Full color TIFF raster.
3831 if (image->colorspace == LabColorspace)
3833 photometric=PHOTOMETRIC_CIELAB;
3834 EncodeLabImage(image,exception);
3837 if (image->colorspace == YCbCrColorspace)
3839 photometric=PHOTOMETRIC_YCBCR;
3840 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
3841 (void) SetImageStorageClass(image,DirectClass,exception);
3842 (void) SetImageDepth(image,8,exception);
3845 photometric=PHOTOMETRIC_RGB;
3846 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
3847 if ((image_info->type != TrueColorType) &&
3848 (image_info->type != TrueColorAlphaType))
3850 if ((image_info->type != PaletteType) &&
3851 (SetImageGray(image,exception) != MagickFalse))
3853 photometric=(uint16) (quantum_info->min_is_white !=
3854 MagickFalse ? PHOTOMETRIC_MINISWHITE :
3855 PHOTOMETRIC_MINISBLACK);
3856 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3857 if ((image->depth == 1) &&
3858 (image->alpha_trait == UndefinedPixelTrait))
3859 SetImageMonochrome(image,exception);
3862 if (image->storage_class == PseudoClass)
3868 Colormapped TIFF raster.
3870 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3871 photometric=PHOTOMETRIC_PALETTE;
3873 while ((GetQuantumRange(depth)+1) < image->colors)
3875 status=SetQuantumDepth(image,quantum_info,depth);
3876 if (status == MagickFalse)
3877 ThrowWriterException(ResourceLimitError,
3878 "MemoryAllocationFailed");
3882 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
3883 if ((compress_tag == COMPRESSION_CCITTFAX3) ||
3884 (compress_tag == COMPRESSION_CCITTFAX4))
3886 if ((photometric != PHOTOMETRIC_MINISWHITE) &&
3887 (photometric != PHOTOMETRIC_MINISBLACK))
3889 compress_tag=COMPRESSION_NONE;
3890 endian=FILLORDER_MSB2LSB;
3893 option=GetImageOption(image_info,"tiff:fill-order");
3894 if (option != (const char *) NULL)
3896 if (LocaleNCompare(option,"msb",3) == 0)
3897 endian=FILLORDER_MSB2LSB;
3898 if (LocaleNCompare(option,"lsb",3) == 0)
3899 endian=FILLORDER_LSB2MSB;
3901 (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
3902 (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
3903 (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
3904 if (image->alpha_trait != UndefinedPixelTrait)
3912 TIFF has a matte channel.
3915 sample_info[0]=EXTRASAMPLE_UNASSALPHA;
3916 option=GetImageOption(image_info,"tiff:alpha");
3917 if (option != (const char *) NULL)
3919 if (LocaleCompare(option,"associated") == 0)
3920 sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
3922 if (LocaleCompare(option,"unspecified") == 0)
3923 sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
3925 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
3926 &samples_per_pixel);
3927 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
3928 (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
3930 if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
3931 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
3933 (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
3934 switch (quantum_info->format)
3936 case FloatingPointQuantumFormat:
3938 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
3939 (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
3940 (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
3943 case SignedQuantumFormat:
3945 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
3948 case UnsignedQuantumFormat:
3950 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
3956 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3957 if (photometric == PHOTOMETRIC_RGB)
3958 if ((image_info->interlace == PlaneInterlace) ||
3959 (image_info->interlace == PartitionInterlace))
3960 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
3962 switch (compress_tag)
3964 case COMPRESSION_JPEG:
3966 #if defined(JPEG_SUPPORT)
3967 if (image_info->quality != UndefinedCompressionQuality)
3968 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
3969 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
3970 if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
3975 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
3976 if (image->colorspace == YCbCrColorspace)
3987 sampling_factor=(const char *) NULL;
3988 value=GetImageProperty(image,"jpeg:sampling-factor",exception);
3989 if (value != (char *) NULL)
3991 sampling_factor=value;
3992 if (image->debug != MagickFalse)
3993 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
3994 " Input sampling-factors=%s",sampling_factor);
3996 if (image_info->sampling_factor != (char *) NULL)
3997 sampling_factor=image_info->sampling_factor;
3998 if (sampling_factor != (const char *) NULL)
4000 flags=ParseGeometry(sampling_factor,&geometry_info);
4001 if ((flags & SigmaValue) == 0)
4002 geometry_info.sigma=geometry_info.rho;
4003 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
4004 geometry_info.rho,(uint16) geometry_info.sigma);
4008 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
4010 if (bits_per_sample == 12)
4011 (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
4015 case COMPRESSION_ADOBE_DEFLATE:
4017 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
4019 if (((photometric == PHOTOMETRIC_RGB) ||
4020 (photometric == PHOTOMETRIC_SEPARATED) ||
4021 (photometric == PHOTOMETRIC_MINISBLACK)) &&
4022 ((bits_per_sample == 8) || (bits_per_sample == 16)))
4023 predictor=PREDICTOR_HORIZONTAL;
4024 (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
4025 image_info->quality == UndefinedCompressionQuality ? 7 :
4026 MagickMin((ssize_t) image_info->quality/10,9)));
4029 case COMPRESSION_CCITTFAX3:
4034 (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
4037 case COMPRESSION_CCITTFAX4:
4039 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
4040 case COMPRESSION_LZMA:
4042 if (((photometric == PHOTOMETRIC_RGB) ||
4043 (photometric == PHOTOMETRIC_SEPARATED) ||
4044 (photometric == PHOTOMETRIC_MINISBLACK)) &&
4045 ((bits_per_sample == 8) || (bits_per_sample == 16)))
4046 predictor=PREDICTOR_HORIZONTAL;
4047 (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
4048 image_info->quality == UndefinedCompressionQuality ? 7 :
4049 MagickMin((ssize_t) image_info->quality/10,9)));
4053 case COMPRESSION_LZW:
4055 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
4057 if (((photometric == PHOTOMETRIC_RGB) ||
4058 (photometric == PHOTOMETRIC_SEPARATED) ||
4059 (photometric == PHOTOMETRIC_MINISBLACK)) &&
4060 ((bits_per_sample == 8) || (bits_per_sample == 16)))
4061 predictor=PREDICTOR_HORIZONTAL;
4064 #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
4065 case COMPRESSION_WEBP:
4067 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
4069 if (((photometric == PHOTOMETRIC_RGB) ||
4070 (photometric == PHOTOMETRIC_SEPARATED) ||
4071 (photometric == PHOTOMETRIC_MINISBLACK)) &&
4072 ((bits_per_sample == 8) || (bits_per_sample == 16)))
4073 predictor=PREDICTOR_HORIZONTAL;
4074 (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,image_info->quality);
4075 if (image_info->quality >= 100)
4076 (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
4080 #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
4081 case COMPRESSION_ZSTD:
4083 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
4085 if (((photometric == PHOTOMETRIC_RGB) ||
4086 (photometric == PHOTOMETRIC_SEPARATED) ||
4087 (photometric == PHOTOMETRIC_MINISBLACK)) &&
4088 ((bits_per_sample == 8) || (bits_per_sample == 16)))
4089 predictor=PREDICTOR_HORIZONTAL;
4090 (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
4098 option=GetImageOption(image_info,"tiff:predictor");
4099 if (option != (const char * ) NULL)
4100 predictor=(uint16) strtol(option,(char **) NULL,10);
4102 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
4103 if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
4109 Set image resolution.
4112 if (image->units == PixelsPerInchResolution)
4114 if (image->units == PixelsPerCentimeterResolution)
4115 units=RESUNIT_CENTIMETER;
4116 (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
4117 (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
4118 (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
4119 if ((image->page.x < 0) || (image->page.y < 0))
4120 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
4121 "TIFF: negative image positions unsupported","%s",image->filename);
4122 if ((image->page.x > 0) && (image->resolution.x > 0.0))
4125 Set horizontal image position.
4127 (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
4128 image->resolution.x);
4130 if ((image->page.y > 0) && (image->resolution.y > 0.0))
4133 Set vertical image position.
4135 (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
4136 image->resolution.y);
4139 if (image->chromaticity.white_point.x != 0.0)
4145 Set image chromaticity.
4147 chromaticity[0]=(float) image->chromaticity.red_primary.x;
4148 chromaticity[1]=(float) image->chromaticity.red_primary.y;
4149 chromaticity[2]=(float) image->chromaticity.green_primary.x;
4150 chromaticity[3]=(float) image->chromaticity.green_primary.y;
4151 chromaticity[4]=(float) image->chromaticity.blue_primary.x;
4152 chromaticity[5]=(float) image->chromaticity.blue_primary.y;
4153 (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
4154 chromaticity[0]=(float) image->chromaticity.white_point.x;
4155 chromaticity[1]=(float) image->chromaticity.white_point.y;
4156 (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
4158 option=GetImageOption(image_info,"tiff:write-layers");
4159 if (IsStringTrue(option) != MagickFalse)
4161 (void) TIFFWritePhotoshopLayers(image,image_info,endian_type,exception);
4164 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
4165 (adjoin != MagickFalse) && (imageListLength > 1))
4167 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
4168 if (image->scene != 0)
4169 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
4172 if (image->orientation != UndefinedOrientation)
4173 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
4175 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
4176 TIFFSetProfiles(tiff,image);
4182 page=(uint16) scene;
4183 pages=(uint16) imageListLength;
4184 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
4185 (adjoin != MagickFalse) && (pages > 1))
4186 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
4187 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
4189 (void) TIFFSetProperties(tiff,adjoin,image,exception);
4190 DisableMSCWarning(4127)
4193 (void) TIFFSetEXIFProperties(tiff,image,exception);
4195 Write image scanlines.
4197 if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
4198 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
4199 quantum_info->endian=LSBEndian;
4200 pixels=(unsigned char *) GetQuantumPixels(quantum_info);
4201 tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);
4202 switch (photometric)
4204 case PHOTOMETRIC_CIELAB:
4205 case PHOTOMETRIC_YCBCR:
4206 case PHOTOMETRIC_RGB:
4211 switch (image_info->interlace)
4216 quantum_type=RGBQuantum;
4217 if (image->alpha_trait != UndefinedPixelTrait)
4218 quantum_type=RGBAQuantum;
4219 for (y=0; y < (ssize_t) image->rows; y++)
4221 register const Quantum
4224 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4225 if (p == (const Quantum *) NULL)
4227 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4228 quantum_type,pixels,exception);
4230 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
4232 if (image->previous == (Image *) NULL)
4234 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
4236 if (status == MagickFalse)
4242 case PlaneInterlace:
4243 case PartitionInterlace:
4246 Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
4248 for (y=0; y < (ssize_t) image->rows; y++)
4250 register const Quantum
4253 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4254 if (p == (const Quantum *) NULL)
4256 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4257 RedQuantum,pixels,exception);
4258 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
4261 if (image->previous == (Image *) NULL)
4263 status=SetImageProgress(image,SaveImageTag,100,400);
4264 if (status == MagickFalse)
4267 for (y=0; y < (ssize_t) image->rows; y++)
4269 register const Quantum
4272 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4273 if (p == (const Quantum *) NULL)
4275 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4276 GreenQuantum,pixels,exception);
4277 if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
4280 if (image->previous == (Image *) NULL)
4282 status=SetImageProgress(image,SaveImageTag,200,400);
4283 if (status == MagickFalse)
4286 for (y=0; y < (ssize_t) image->rows; y++)
4288 register const Quantum
4291 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4292 if (p == (const Quantum *) NULL)
4294 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4295 BlueQuantum,pixels,exception);
4296 if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
4299 if (image->previous == (Image *) NULL)
4301 status=SetImageProgress(image,SaveImageTag,300,400);
4302 if (status == MagickFalse)
4305 if (image->alpha_trait != UndefinedPixelTrait)
4306 for (y=0; y < (ssize_t) image->rows; y++)
4308 register const Quantum
4311 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4312 if (p == (const Quantum *) NULL)
4314 length=ExportQuantumPixels(image,(CacheView *) NULL,
4315 quantum_info,AlphaQuantum,pixels,exception);
4316 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
4319 if (image->previous == (Image *) NULL)
4321 status=SetImageProgress(image,SaveImageTag,400,400);
4322 if (status == MagickFalse)
4330 case PHOTOMETRIC_SEPARATED:
4335 quantum_type=CMYKQuantum;
4336 if (image->alpha_trait != UndefinedPixelTrait)
4337 quantum_type=CMYKAQuantum;
4338 if (image->colorspace != CMYKColorspace)
4339 (void) TransformImageColorspace(image,CMYKColorspace,exception);
4340 for (y=0; y < (ssize_t) image->rows; y++)
4342 register const Quantum
4345 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4346 if (p == (const Quantum *) NULL)
4348 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4349 quantum_type,pixels,exception);
4350 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
4352 if (image->previous == (Image *) NULL)
4354 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
4356 if (status == MagickFalse)
4362 case PHOTOMETRIC_PALETTE:
4370 Colormapped TIFF image.
4372 red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
4373 green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
4374 blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
4375 if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
4376 (blue == (uint16 *) NULL))
4378 if (red != (uint16 *) NULL)
4379 red=(uint16 *) RelinquishMagickMemory(red);
4380 if (green != (uint16 *) NULL)
4381 green=(uint16 *) RelinquishMagickMemory(green);
4382 if (blue != (uint16 *) NULL)
4383 blue=(uint16 *) RelinquishMagickMemory(blue);
4384 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
4387 Initialize TIFF colormap.
4389 (void) memset(red,0,65536*sizeof(*red));
4390 (void) memset(green,0,65536*sizeof(*green));
4391 (void) memset(blue,0,65536*sizeof(*blue));
4392 for (i=0; i < (ssize_t) image->colors; i++)
4394 red[i]=ScaleQuantumToShort(image->colormap[i].red);
4395 green[i]=ScaleQuantumToShort(image->colormap[i].green);
4396 blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
4398 (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
4399 red=(uint16 *) RelinquishMagickMemory(red);
4400 green=(uint16 *) RelinquishMagickMemory(green);
4401 blue=(uint16 *) RelinquishMagickMemory(blue);
4406 Convert PseudoClass packets to contiguous grayscale scanlines.
4408 quantum_type=IndexQuantum;
4409 if (image->alpha_trait != UndefinedPixelTrait)
4411 if (photometric != PHOTOMETRIC_PALETTE)
4412 quantum_type=GrayAlphaQuantum;
4414 quantum_type=IndexAlphaQuantum;
4417 if (photometric != PHOTOMETRIC_PALETTE)
4418 quantum_type=GrayQuantum;
4419 for (y=0; y < (ssize_t) image->rows; y++)
4421 register const Quantum
4424 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
4425 if (p == (const Quantum *) NULL)
4427 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
4428 quantum_type,pixels,exception);
4429 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
4431 if (image->previous == (Image *) NULL)
4433 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
4435 if (status == MagickFalse)
4442 quantum_info=DestroyQuantumInfo(quantum_info);
4443 if (image->colorspace == LabColorspace)
4444 DecodeLabImage(image,exception);
4445 DestroyTIFFInfo(&tiff_info);
4446 DisableMSCWarning(4127)
4447 if (0 && (image_info->verbose != MagickFalse))
4449 TIFFPrintDirectory(tiff,stdout,MagickFalse);
4450 if (TIFFWriteDirectory(tiff) == 0)
4455 image=SyncNextImageInList(image);
4456 if (image == (Image *) NULL)
4458 status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
4459 if (status == MagickFalse)
4461 } while (adjoin != MagickFalse);