2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % TTTTT IIIII FFFFF FFFFF %
13 % Read/Write TIFF Image Format %
20 % Copyright 1999-2014 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 % http://www.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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 #include "MagickCore/studio.h"
43 #include "MagickCore/artifact.h"
44 #include "MagickCore/attribute.h"
45 #include "MagickCore/blob.h"
46 #include "MagickCore/blob-private.h"
47 #include "MagickCore/cache.h"
48 #include "MagickCore/color.h"
49 #include "MagickCore/color-private.h"
50 #include "MagickCore/colormap.h"
51 #include "MagickCore/colorspace.h"
52 #include "MagickCore/colorspace-private.h"
53 #include "MagickCore/constitute.h"
54 #include "MagickCore/enhance.h"
55 #include "MagickCore/exception.h"
56 #include "MagickCore/exception-private.h"
57 #include "MagickCore/geometry.h"
58 #include "MagickCore/image.h"
59 #include "MagickCore/image-private.h"
60 #include "MagickCore/list.h"
61 #include "MagickCore/log.h"
62 #include "MagickCore/magick.h"
63 #include "MagickCore/memory_.h"
64 #include "MagickCore/module.h"
65 #include "MagickCore/monitor.h"
66 #include "MagickCore/monitor-private.h"
67 #include "MagickCore/option.h"
68 #include "MagickCore/pixel-accessor.h"
69 #include "MagickCore/pixel-private.h"
70 #include "MagickCore/property.h"
71 #include "MagickCore/quantum.h"
72 #include "MagickCore/quantum-private.h"
73 #include "MagickCore/profile.h"
74 #include "MagickCore/resize.h"
75 #include "MagickCore/resource_.h"
76 #include "MagickCore/semaphore.h"
77 #include "MagickCore/splay-tree.h"
78 #include "MagickCore/static.h"
79 #include "MagickCore/statistic.h"
80 #include "MagickCore/string_.h"
81 #include "MagickCore/string-private.h"
82 #include "MagickCore/thread_.h"
83 #include "MagickCore/token.h"
84 #include "MagickCore/utility.h"
85 #if defined(MAGICKCORE_TIFF_DELEGATE)
86 # if defined(MAGICKCORE_HAVE_TIFFCONF_H)
87 # include "tiffconf.h"
91 # if !defined(COMPRESSION_ADOBE_DEFLATE)
92 # define COMPRESSION_ADOBE_DEFLATE 8
94 # if !defined(PREDICTOR_HORIZONTAL)
95 # define PREDICTOR_HORIZONTAL 2
97 # if !defined(TIFFTAG_COPYRIGHT)
98 # define TIFFTAG_COPYRIGHT 33432
100 # if !defined(TIFFTAG_OPIIMAGEID)
101 # define TIFFTAG_OPIIMAGEID 32781
105 Typedef declarations.
107 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
108 typedef struct _ExifInfo
119 static const ExifInfo
121 { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
122 { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
123 { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
124 { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
125 { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
126 { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
127 { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
128 { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
129 { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
130 { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
131 { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
132 { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
133 { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
134 { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
135 { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
136 { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
137 { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
138 { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
139 { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
140 { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
141 { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
142 { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
143 { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
144 { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
145 { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
146 { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
147 { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
148 { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
149 { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
150 { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
151 { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
152 { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
153 { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
154 { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
155 { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
156 { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
157 { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
158 { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
159 { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
160 { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
161 { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
162 { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
163 { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
164 { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
165 { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
166 { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
167 { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
168 { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
169 { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
170 { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
171 { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
172 { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
173 { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
174 { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
175 { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
176 { 0, 0, 0, (char *) NULL }
179 #endif /* MAGICKCORE_TIFF_DELEGATE */
184 static MagickThreadKey
188 *tiff_semaphore = (SemaphoreInfo *) NULL;
190 static volatile MagickBooleanType
191 instantiate_key = MagickFalse;
194 Forward declarations.
196 #if defined(MAGICKCORE_TIFF_DELEGATE)
198 ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
200 static MagickBooleanType
201 WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
202 WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
203 WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
217 % IsTIFF() returns MagickTrue if the image format type, identified by the
218 % magick string, is TIFF.
220 % The format of the IsTIFF method is:
222 % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
224 % A description of each parameter follows:
226 % o magick: compare image format pattern against these bytes.
228 % o length: Specifies the length of the magick string.
231 static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
235 if (memcmp(magick,"\115\115\000\052",4) == 0)
237 if (memcmp(magick,"\111\111\052\000",4) == 0)
239 #if defined(TIFF_VERSION_BIG)
242 if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
244 if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
250 #if defined(MAGICKCORE_TIFF_DELEGATE)
252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
256 % R e a d G R O U P 4 I m a g e %
260 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
262 % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
263 % allocates the memory necessary for the new Image structure and returns a
264 % pointer to the new image.
266 % The format of the ReadGROUP4Image method is:
268 % Image *ReadGROUP4Image(const ImageInfo *image_info,
269 % ExceptionInfo *exception)
271 % A description of each parameter follows:
273 % o image_info: the image info.
275 % o exception: return any errors or warnings in this structure.
279 static inline size_t WriteLSBLong(FILE *file,const size_t value)
284 buffer[0]=(unsigned char) value;
285 buffer[1]=(unsigned char) (value >> 8);
286 buffer[2]=(unsigned char) (value >> 16);
287 buffer[3]=(unsigned char) (value >> 24);
288 return(fwrite(buffer,1,4,file));
291 static Image *ReadGROUP4Image(const ImageInfo *image_info,
292 ExceptionInfo *exception)
295 filename[MaxTextExtent];
323 assert(image_info != (const ImageInfo *) NULL);
324 assert(image_info->signature == MagickSignature);
325 if (image_info->debug != MagickFalse)
326 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
327 image_info->filename);
328 assert(exception != (ExceptionInfo *) NULL);
329 assert(exception->signature == MagickSignature);
330 image=AcquireImage(image_info,exception);
331 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
332 if (status == MagickFalse)
334 image=DestroyImageList(image);
335 return((Image *) NULL);
338 Write raw CCITT Group 4 wrapped as a TIFF image file.
341 unique_file=AcquireUniqueFileResource(filename);
342 if (unique_file != -1)
343 file=fdopen(unique_file,"wb");
344 if ((unique_file == -1) || (file == (FILE *) NULL))
345 ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
346 length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
347 length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
348 length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
349 length=WriteLSBLong(file,image->columns);
350 length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
351 length=WriteLSBLong(file,image->rows);
352 length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
353 length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
354 length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
355 length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
356 strip_offset=10+(12*14)+4+8;
357 length=WriteLSBLong(file,(size_t) strip_offset);
358 length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
359 length=WriteLSBLong(file,(size_t) image_info->orientation);
360 length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
361 length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
362 length=WriteLSBLong(file,image->rows);
363 length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
364 offset=(ssize_t) ftell(file)-4;
365 length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
366 length=WriteLSBLong(file,(size_t) (strip_offset-8));
367 length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
368 length=WriteLSBLong(file,(size_t) (strip_offset-8));
369 length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
370 length=fwrite("\000\000\000\000",1,4,file);
371 length=WriteLSBLong(file,(long) image->resolution.x);
372 length=WriteLSBLong(file,1);
373 for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
374 (void) fputc(c,file);
375 offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
376 length=WriteLSBLong(file,(unsigned int) length);
378 (void) CloseBlob(image);
379 image=DestroyImage(image);
383 read_info=CloneImageInfo((ImageInfo *) NULL);
384 (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
385 image=ReadTIFFImage(read_info,exception);
386 read_info=DestroyImageInfo(read_info);
387 if (image != (Image *) NULL)
389 (void) CopyMagickString(image->filename,image_info->filename,
391 (void) CopyMagickString(image->magick_filename,image_info->filename,
393 (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
395 (void) RelinquishUniqueFileResource(filename);
400 #if defined(MAGICKCORE_TIFF_DELEGATE)
402 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
406 % R e a d T I F F I m a g e %
410 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
412 % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
413 % memory necessary for the new Image structure and returns a pointer to the
416 % The format of the ReadTIFFImage method is:
418 % Image *ReadTIFFImage(const ImageInfo *image_info,
419 % ExceptionInfo *exception)
421 % A description of each parameter follows:
423 % o image_info: the image info.
425 % o exception: return any errors or warnings in this structure.
429 static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
441 image_view=AcquireAuthenticCacheView(image,exception);
442 for (y=0; y < (ssize_t) image->rows; y++)
450 if (status == MagickFalse)
452 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
453 if (q == (Quantum *) NULL)
458 for (x=0; x < (ssize_t) image->columns; x++)
464 a=QuantumScale*GetPixela(image,q)+0.5;
467 b=QuantumScale*GetPixelb(image,q)+0.5;
470 SetPixela(image,QuantumRange*a,q);
471 SetPixelb(image,QuantumRange*b,q);
472 q+=GetPixelChannels(image);
474 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
477 image_view=DestroyCacheView(image_view);
481 static inline size_t MagickMax(const size_t x,const size_t y)
488 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
495 static MagickBooleanType ReadProfile(Image *image,const char *name,
496 unsigned char *datum,ssize_t length,ExceptionInfo *exception)
510 if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"xmp") != 0))
512 for (i=0; i < (length-4); i+=2)
513 if (LocaleNCompare((char *) (datum+i),"8BIM",4) == 0)
522 profile=BlobToStringInfo(datum+i,(size_t) length);
523 if (profile == (StringInfo *) NULL)
524 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
526 status=SetImageProfile(image,name,profile,exception);
527 profile=DestroyStringInfo(profile);
528 if (status == MagickFalse)
529 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
534 #if defined(__cplusplus) || defined(c_plusplus)
538 static int TIFFCloseBlob(thandle_t image)
540 (void) CloseBlob((Image *) image);
544 static void TIFFErrors(const char *module,const char *format,va_list error)
547 message[MaxTextExtent];
552 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
553 (void) vsnprintf(message,MaxTextExtent,format,error);
555 (void) vsprintf(message,format,error);
557 (void) ConcatenateMagickString(message,".",MaxTextExtent);
558 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
559 if (exception != (ExceptionInfo *) NULL)
560 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
564 static toff_t TIFFGetBlobSize(thandle_t image)
566 return((toff_t) GetBlobSize((Image *) image));
569 static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
577 #if defined(TIFFTAG_ICCPROFILE)
579 if (TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1)
580 (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
582 #if defined(TIFFTAG_PHOTOSHOP)
584 if (TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1)
585 (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
587 #if defined(TIFFTAG_RICHTIFFIPTC)
589 if (TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1)
591 if (TIFFIsByteSwapped(tiff) != 0)
592 TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
593 (void) ReadProfile(image,"iptc",profile,4L*length,exception);
596 #if defined(TIFFTAG_XMLPACKET)
598 if (TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1)
599 (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
602 if (TIFFGetField(tiff,37724,&length,&profile) == 1)
603 (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
604 if (TIFFGetField(tiff,34118,&length,&profile) == 1)
605 (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,exception);
608 static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
611 message[MaxTextExtent],
617 if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
618 (void) SetImageProperty(image,"tiff:artist",text,exception);
619 if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
620 (void) SetImageProperty(image,"tiff:copyright",text,exception);
621 if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
622 (void) SetImageProperty(image,"tiff:timestamp",text,exception);
623 if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
624 (void) SetImageProperty(image,"tiff:document",text,exception);
625 if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
626 (void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
627 if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
628 (void) SetImageProperty(image,"comment",text,exception);
629 if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
630 (void) SetImageProperty(image,"tiff:make",text,exception);
631 if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
632 (void) SetImageProperty(image,"tiff:model",text,exception);
633 if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
635 if (count >= MaxTextExtent)
636 count=MaxTextExtent-1;
637 (void) CopyMagickString(message,text,count+1);
638 (void) SetImageProperty(image,"tiff:image-id",message,exception);
640 if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
641 (void) SetImageProperty(image,"label",text,exception);
642 if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
643 (void) SetImageProperty(image,"tiff:software",text,exception);
644 if (TIFFGetField(tiff,33423,&count,&text) == 1)
646 if (count >= MaxTextExtent)
647 count=MaxTextExtent-1;
648 (void) CopyMagickString(message,text,count+1);
649 (void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
651 if (TIFFGetField(tiff,36867,&count,&text) == 1)
653 if (count >= MaxTextExtent)
654 count=MaxTextExtent-1;
655 (void) CopyMagickString(message,text,count+1);
656 (void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
660 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
661 ExceptionInfo *exception)
663 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
665 value[MaxTextExtent];
673 #if defined(TIFF_VERSION_BIG)
684 Read EXIF properties.
687 if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) == 0)
689 directory=TIFFCurrentDirectory(tiff);
690 if (TIFFReadEXIFDirectory(tiff,offset) == 0)
692 directory=TIFFCurrentDirectory(tiff);
696 for (i=0; exif_info[i].tag != 0; i++)
699 switch (exif_info[i].type)
707 if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) != 0) &&
708 (ascii != (char *) NULL) && (*ascii != '\0'))
709 (void) CopyMagickString(value,ascii,MaxTextExtent);
714 if (exif_info[i].variable_length != 0)
719 if (TIFFGetField(tiff,exif_info[i].tag,&sans,&shorty,&sans,&sans) != 0)
720 (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty[0]);
728 if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) != 0)
729 (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
739 if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) != 0)
740 (void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
743 #if defined(TIFF_VERSION_BIG)
750 if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) != 0)
751 (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
752 ((MagickOffsetType) long8y));
764 if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) != 0)
765 (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
774 if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) != 0)
775 (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
782 (void) SetImageProperty(image,exif_info[i].property,value,exception);
784 TIFFSetDirectory(tiff,directory);
791 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
793 *base=(tdata_t *) GetBlobStreamData((Image *) image);
794 if (*base != (tdata_t *) NULL)
795 *size=(toff_t) GetBlobSize((Image *) image);
796 if (*base != (tdata_t *) NULL)
801 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
806 count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
807 (unsigned char *) data);
811 static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
812 tsample_t sample,ssize_t row,tdata_t scanline)
817 (void) bits_per_sample;
818 status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
822 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
824 return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
827 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
834 static void TIFFWarnings(const char *module,const char *format,va_list warning)
837 message[MaxTextExtent];
842 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
843 (void) vsnprintf(message,MaxTextExtent,format,warning);
845 (void) vsprintf(message,format,warning);
847 (void) ConcatenateMagickString(message,".",MaxTextExtent);
848 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
849 if (exception != (ExceptionInfo *) NULL)
850 (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
851 message,"`%s'",module);
854 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
859 count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
860 (unsigned char *) data);
864 #if defined(__cplusplus) || defined(c_plusplus)
868 static Image *ReadTIFFImage(const ImageInfo *image_info,
869 ExceptionInfo *exception)
873 ReadSingleSampleMethod,
956 assert(image_info != (const ImageInfo *) NULL);
957 assert(image_info->signature == MagickSignature);
958 if (image_info->debug != MagickFalse)
959 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
960 image_info->filename);
961 assert(exception != (ExceptionInfo *) NULL);
962 assert(exception->signature == MagickSignature);
963 image=AcquireImage(image_info,exception);
964 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
965 if (status == MagickFalse)
967 image=DestroyImageList(image);
968 return((Image *) NULL);
970 (void) MagickSetThreadValue(tiff_exception,exception);
971 error_handler=TIFFSetErrorHandler(TIFFErrors);
972 warning_handler=TIFFSetWarningHandler(TIFFWarnings);
973 tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
974 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
976 if (tiff == (TIFF *) NULL)
978 (void) TIFFSetWarningHandler(warning_handler);
979 (void) TIFFSetErrorHandler(error_handler);
980 image=DestroyImageList(image);
981 return((Image *) NULL);
983 debug=IsEventLogging();
985 if (image_info->number_scenes != 0)
988 Generate blank images for subimage specification (e.g. image.tif[4].
990 for (i=0; i < (ssize_t) image_info->scene; i++)
992 (void) TIFFReadDirectory(tiff);
993 AcquireNextImage(image_info,image,exception);
994 if (GetNextImageInList(image) == (Image *) NULL)
996 image=DestroyImageList(image);
997 return((Image *) NULL);
999 image=SyncNextImageInList(image);
1004 DisableMSCWarning(4127)
1005 if (0 && (image_info->verbose != MagickFalse))
1007 TIFFPrintDirectory(tiff,stdout,MagickFalse);
1008 #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
1009 (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
1010 "lsb" : "msb",exception);
1012 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
1013 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
1014 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
1015 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGELENGTH,&height);
1016 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
1017 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace);
1018 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample);
1019 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format);
1020 if (sample_format == SAMPLEFORMAT_IEEEFP)
1021 (void) SetImageProperty(image,"quantum:format","floating-point",
1023 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value);
1024 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value);
1025 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric);
1026 switch (photometric)
1028 case PHOTOMETRIC_MINISBLACK:
1030 (void) SetImageProperty(image,"tiff:photometric","min-is-black",
1034 case PHOTOMETRIC_MINISWHITE:
1036 (void) SetImageProperty(image,"tiff:photometric","min-is-white",
1040 case PHOTOMETRIC_PALETTE:
1042 (void) SetImageProperty(image,"tiff:photometric","palette",exception);
1045 case PHOTOMETRIC_RGB:
1047 (void) SetImageProperty(image,"tiff:photometric","RGB",exception);
1050 case PHOTOMETRIC_CIELAB:
1052 (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
1055 case PHOTOMETRIC_SEPARATED:
1057 (void) SetImageProperty(image,"tiff:photometric","separated",exception);
1060 case PHOTOMETRIC_YCBCR:
1062 (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
1067 (void) SetImageProperty(image,"tiff:photometric","unknown",exception);
1071 if (image->debug != MagickFalse)
1073 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
1074 (unsigned int) width,(unsigned int) height);
1075 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
1077 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1078 "Bits per sample: %u",bits_per_sample);
1079 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1080 "Min sample value: %u",min_sample_value);
1081 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1082 "Max sample value: %u",max_sample_value);
1083 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
1084 "interpretation: %s",GetImageProperty(image,"tiff:photometric",
1087 image->columns=(size_t) width;
1088 image->rows=(size_t) height;
1089 image->depth=(size_t) bits_per_sample;
1090 if (image->debug != MagickFalse)
1091 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
1092 (double) image->depth);
1093 image->endian=MSBEndian;
1094 if (endian == FILLORDER_LSB2MSB)
1095 image->endian=LSBEndian;
1096 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1097 (photometric == PHOTOMETRIC_MINISWHITE))
1098 SetImageColorspace(image,GRAYColorspace,exception);
1099 if (photometric == PHOTOMETRIC_SEPARATED)
1100 SetImageColorspace(image,CMYKColorspace,exception);
1101 if (photometric == PHOTOMETRIC_CIELAB)
1102 SetImageColorspace(image,LabColorspace,exception);
1103 TIFFGetProfiles(tiff,image,exception);
1104 TIFFGetProperties(tiff,image,exception);
1105 option=GetImageOption(image_info,"tiff:exif-properties");
1106 if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
1107 TIFFGetEXIFProperties(tiff,image,exception);
1108 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
1109 &samples_per_pixel);
1110 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
1111 x_resolution=(float) image->resolution.x;
1112 y_resolution=(float) image->resolution.y;
1113 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution);
1114 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
1115 image->resolution.x=x_resolution;
1116 image->resolution.y=y_resolution;
1117 x_position=(float) PerceptibleReciprocal(x_resolution)*image->page.x;
1118 y_position=(float) PerceptibleReciprocal(y_resolution)*image->page.y;
1119 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
1120 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
1121 image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
1122 image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
1123 image->orientation=(OrientationType) orientation;
1124 chromaticity=(float *) NULL;
1125 (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
1126 if (chromaticity != (float *) NULL)
1128 image->chromaticity.white_point.x=chromaticity[0];
1129 image->chromaticity.white_point.y=chromaticity[1];
1131 chromaticity=(float *) NULL;
1132 (void) TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity);
1133 if (chromaticity != (float *) NULL)
1135 image->chromaticity.red_primary.x=chromaticity[0];
1136 image->chromaticity.red_primary.y=chromaticity[1];
1137 image->chromaticity.green_primary.x=chromaticity[2];
1138 image->chromaticity.green_primary.y=chromaticity[3];
1139 image->chromaticity.blue_primary.x=chromaticity[4];
1140 image->chromaticity.blue_primary.y=chromaticity[5];
1142 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
1143 if ((compress_tag != COMPRESSION_NONE) &&
1144 (TIFFIsCODECConfigured(compress_tag) == 0))
1147 ThrowReaderException(CoderError,"CompressNotSupported");
1150 switch (compress_tag)
1152 case COMPRESSION_NONE: image->compression=NoCompression; break;
1153 case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1154 case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1155 case COMPRESSION_JPEG:
1157 image->compression=JPEGCompression;
1158 #if defined(JPEG_SUPPORT)
1161 sampling_factor[MaxTextExtent];
1167 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
1168 &horizontal,&vertical);
1169 (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
1170 horizontal,vertical);
1171 (void) SetImageProperty(image,"jpeg:sampling-factor",
1172 sampling_factor,exception);
1173 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1174 "Sampling Factors: %s",sampling_factor);
1179 case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1180 #if defined(COMPRESSION_LZMA)
1181 case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1183 case COMPRESSION_LZW: image->compression=LZWCompression; break;
1184 case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1185 case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1186 default: image->compression=RLECompression; break;
1189 Allocate memory for the image and pixel buffer.
1191 quantum_info=AcquireQuantumInfo(image_info,image);
1192 if (quantum_info == (QuantumInfo *) NULL)
1195 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1197 if (sample_format == SAMPLEFORMAT_UINT)
1198 status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1199 if (sample_format == SAMPLEFORMAT_INT)
1200 status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1201 if (sample_format == SAMPLEFORMAT_IEEEFP)
1202 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1203 if (status == MagickFalse)
1205 quantum_info=DestroyQuantumInfo(quantum_info);
1207 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1210 switch (photometric)
1212 case PHOTOMETRIC_MINISBLACK:
1214 quantum_info->min_is_white=MagickFalse;
1217 case PHOTOMETRIC_MINISWHITE:
1219 quantum_info->min_is_white=MagickTrue;
1225 associated_alpha=MagickFalse;
1227 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1229 if (extra_samples == 0)
1231 if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1232 image->alpha_trait=BlendPixelTrait;
1235 for (i=0; i < extra_samples; i++)
1237 image->alpha_trait=BlendPixelTrait;
1238 if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1239 SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1241 option=GetImageOption(image_info,"tiff:alpha");
1242 if (option != (const char *) NULL)
1243 associated_alpha=LocaleCompare(option,"associated") == 0 ? MagickTrue :
1245 if (image->alpha_trait == BlendPixelTrait)
1246 (void) SetImageProperty(image,"tiff:alpha",
1247 associated_alpha != MagickFalse ? "associated" : "unassociated",
1249 if ((photometric == PHOTOMETRIC_PALETTE) &&
1250 (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1255 colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1256 if (AcquireImageColormap(image,colors,exception) == MagickFalse)
1259 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1262 if (units == RESUNIT_INCH)
1263 image->units=PixelsPerInchResolution;
1264 if (units == RESUNIT_CENTIMETER)
1265 image->units=PixelsPerCentimeterResolution;
1266 value=(unsigned short) image->scene;
1267 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages);
1269 if (image_info->ping != MagickFalse)
1271 if (image_info->number_scenes != 0)
1272 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1274 goto next_tiff_frame;
1276 method=ReadGenericMethod;
1277 if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) != 0)
1280 value[MaxTextExtent];
1282 method=ReadStripMethod;
1283 (void) FormatLocaleString(value,MaxTextExtent,"%u",
1284 (unsigned int) rows_per_strip);
1285 (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
1287 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
1288 method=ReadRGBAMethod;
1289 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
1290 method=ReadCMYKAMethod;
1291 if ((photometric != PHOTOMETRIC_RGB) &&
1292 (photometric != PHOTOMETRIC_CIELAB) &&
1293 (photometric != PHOTOMETRIC_SEPARATED))
1294 method=ReadGenericMethod;
1295 if (image->storage_class == PseudoClass)
1296 method=ReadSingleSampleMethod;
1297 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1298 (photometric == PHOTOMETRIC_MINISWHITE))
1299 method=ReadSingleSampleMethod;
1300 if ((photometric != PHOTOMETRIC_SEPARATED) &&
1301 (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1302 method=ReadGenericMethod;
1303 if (image->compression == JPEGCompression)
1304 method=ReadGenericMethod;
1305 if (TIFFIsTiled(tiff) != MagickFalse)
1306 method=ReadTileMethod;
1307 quantum_info->endian=LSBEndian;
1308 quantum_type=RGBQuantum;
1309 pixels=GetQuantumPixels(quantum_info);
1312 case ReadSingleSampleMethod:
1315 Convert TIFF image to PseudoClass MIFF image.
1317 if ((image->storage_class == PseudoClass) &&
1318 (photometric == PHOTOMETRIC_PALETTE))
1329 Initialize colormap.
1331 red_colormap=(uint16 *) NULL;
1332 green_colormap=(uint16 *) NULL;
1333 blue_colormap=(uint16 *) NULL;
1334 (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1335 &green_colormap,&blue_colormap);
1336 if ((red_colormap != (uint16 *) NULL) &&
1337 (green_colormap != (uint16 *) NULL) &&
1338 (blue_colormap != (uint16 *) NULL))
1340 range=255; /* might be old style 8-bit colormap */
1341 for (i=0; i < (ssize_t) image->colors; i++)
1342 if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1343 (blue_colormap[i] >= 256))
1348 for (i=0; i < (ssize_t) image->colors; i++)
1350 image->colormap[i].red=ClampToQuantum(((double)
1351 QuantumRange*red_colormap[i])/range);
1352 image->colormap[i].green=ClampToQuantum(((double)
1353 QuantumRange*green_colormap[i])/range);
1354 image->colormap[i].blue=ClampToQuantum(((double)
1355 QuantumRange*blue_colormap[i])/range);
1359 quantum_type=IndexQuantum;
1360 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1361 if (image->alpha_trait == BlendPixelTrait)
1363 if (image->storage_class != PseudoClass)
1365 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1367 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1371 quantum_type=IndexAlphaQuantum;
1372 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1376 if (image->storage_class != PseudoClass)
1378 quantum_type=GrayQuantum;
1379 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1381 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1382 if (status == MagickFalse)
1385 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1387 pixels=GetQuantumPixels(quantum_info);
1388 for (y=0; y < (ssize_t) image->rows; y++)
1396 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1399 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1400 if (q == (Quantum *) NULL)
1402 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1403 quantum_type,pixels,exception);
1405 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1407 if (image->previous == (Image *) NULL)
1409 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1411 if (status == MagickFalse)
1417 case ReadRGBAMethod:
1420 Convert TIFF image to DirectClass MIFF image.
1422 pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1423 quantum_type=RGBQuantum;
1424 if (image->alpha_trait == BlendPixelTrait)
1426 quantum_type=RGBAQuantum;
1427 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1429 if (image->colorspace == CMYKColorspace)
1431 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1432 quantum_type=CMYKQuantum;
1433 if (image->alpha_trait == BlendPixelTrait)
1435 quantum_type=CMYKAQuantum;
1436 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1439 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1440 if (status == MagickFalse)
1443 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1445 pixels=GetQuantumPixels(quantum_info);
1446 for (y=0; y < (ssize_t) image->rows; y++)
1454 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1457 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1458 if (q == (Quantum *) NULL)
1460 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1461 quantum_type,pixels,exception);
1462 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1464 if (image->previous == (Image *) NULL)
1466 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1468 if (status == MagickFalse)
1474 case ReadCMYKAMethod:
1477 Convert TIFF image to DirectClass MIFF image.
1479 for (i=0; i < (ssize_t) samples_per_pixel; i++)
1481 for (y=0; y < (ssize_t) image->rows; y++)
1489 status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1493 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1494 if (q == (Quantum *) NULL)
1496 if (image->colorspace != CMYKColorspace)
1499 case 0: quantum_type=RedQuantum; break;
1500 case 1: quantum_type=GreenQuantum; break;
1501 case 2: quantum_type=BlueQuantum; break;
1502 case 3: quantum_type=AlphaQuantum; break;
1503 default: quantum_type=UndefinedQuantum; break;
1508 case 0: quantum_type=CyanQuantum; break;
1509 case 1: quantum_type=MagentaQuantum; break;
1510 case 2: quantum_type=YellowQuantum; break;
1511 case 3: quantum_type=BlackQuantum; break;
1512 case 4: quantum_type=AlphaQuantum; break;
1513 default: quantum_type=UndefinedQuantum; break;
1515 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1516 quantum_type,pixels,exception);
1517 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1520 if (image->previous == (Image *) NULL)
1522 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1524 if (status == MagickFalse)
1530 case ReadStripMethod:
1536 Convert stripped TIFF image to DirectClass MIFF image.
1540 for (y=0; y < (ssize_t) image->rows; y++)
1548 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1549 if (q == (Quantum *) NULL)
1553 if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1555 i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1559 p=((uint32 *) pixels)+image->columns*i;
1560 for (x=0; x < (ssize_t) image->columns; x++)
1562 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1564 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1566 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1568 if (image->alpha_trait == BlendPixelTrait)
1569 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1572 q+=GetPixelChannels(image);
1574 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1576 if (image->previous == (Image *) NULL)
1578 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1580 if (status == MagickFalse)
1586 case ReadTileMethod:
1600 Convert tiled TIFF image to DirectClass MIFF image.
1602 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) == 0) ||
1603 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) == 0))
1606 ThrowReaderException(CoderError,"ImageIsNotTiled");
1608 (void) SetImageStorageClass(image,DirectClass,exception);
1609 number_pixels=columns*rows;
1610 tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
1611 sizeof(*tile_pixels));
1612 if (tile_pixels == (uint32 *) NULL)
1615 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1617 for (y=0; y < (ssize_t) image->rows; y+=rows)
1630 rows_remaining=image->rows-y;
1631 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1632 rows_remaining=rows;
1633 tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1635 if (tile == (Quantum *) NULL)
1637 for (x=0; x < (ssize_t) image->columns; x+=columns)
1643 if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1645 columns_remaining=image->columns-x;
1646 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1647 columns_remaining=columns;
1648 p=tile_pixels+(rows-rows_remaining)*columns;
1649 q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1651 for (row=rows_remaining; row > 0; row--)
1653 if (image->alpha_trait == BlendPixelTrait)
1654 for (column=columns_remaining; column > 0; column--)
1656 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1658 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1660 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1662 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1665 q+=GetPixelChannels(image);
1668 for (column=columns_remaining; column > 0; column--)
1670 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1672 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1674 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1677 q+=GetPixelChannels(image);
1679 p+=columns-columns_remaining;
1680 q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1683 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1685 if (image->previous == (Image *) NULL)
1687 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1689 if (status == MagickFalse)
1693 tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
1696 case ReadGenericMethod:
1709 Convert TIFF image to DirectClass MIFF image.
1711 number_pixels=(MagickSizeType) image->columns*image->rows;
1712 if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
1713 (number_pixels*sizeof(uint32))))
1716 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1718 pixel_info=AcquireVirtualMemory(image->columns,image->rows*
1720 if (pixel_info == (MemoryInfo *) NULL)
1723 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1725 pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
1726 (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
1727 (uint32) image->rows,(uint32 *) pixels,0);
1729 Convert image to DirectClass pixel packets.
1731 p=pixels+number_pixels-1;
1732 for (y=0; y < (ssize_t) image->rows; y++)
1740 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1741 if (q == (Quantum *) NULL)
1743 q+=GetPixelChannels(image)*(image->columns-1);
1744 for (x=0; x < (ssize_t) image->columns; x++)
1746 SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),
1748 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1750 SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),
1752 if (image->alpha_trait == BlendPixelTrait)
1753 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1756 q-=GetPixelChannels(image);
1758 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1760 if (image->previous == (Image *) NULL)
1762 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1764 if (status == MagickFalse)
1768 pixel_info=RelinquishVirtualMemory(pixel_info);
1772 SetQuantumImageType(image,quantum_type);
1774 quantum_info=DestroyQuantumInfo(quantum_info);
1775 if (photometric == PHOTOMETRIC_CIELAB)
1776 DecodeLabImage(image,exception);
1777 if ((photometric == PHOTOMETRIC_LOGL) ||
1778 (photometric == PHOTOMETRIC_MINISBLACK) ||
1779 (photometric == PHOTOMETRIC_MINISWHITE))
1781 image->type=GrayscaleType;
1782 if (bits_per_sample == 1)
1783 image->type=BilevelType;
1785 if (image->storage_class == PseudoClass)
1786 image->depth=GetImageDepth(image,exception);
1788 Proceed to next image.
1790 if (image_info->number_scenes != 0)
1791 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1793 status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1794 if (status != MagickFalse)
1797 Allocate next image structure.
1799 AcquireNextImage(image_info,image,exception);
1800 if (GetNextImageInList(image) == (Image *) NULL)
1802 image=DestroyImageList(image);
1803 return((Image *) NULL);
1805 image=SyncNextImageInList(image);
1806 status=SetImageProgress(image,LoadImagesTag,image->scene-1,
1808 if (status == MagickFalse)
1811 } while (status != MagickFalse);
1812 (void) TIFFSetWarningHandler(warning_handler);
1813 (void) TIFFSetErrorHandler(error_handler);
1815 return(GetFirstImageInList(image));
1820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1824 % R e g i s t e r T I F F I m a g e %
1828 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1830 % RegisterTIFFImage() adds properties for the TIFF image format to
1831 % the list of supported formats. The properties include the image format
1832 % tag, a method to read and/or write the format, whether the format
1833 % supports the saving of more than one frame to the same file or blob,
1834 % whether the format supports native in-memory I/O, and a brief
1835 % description of the format.
1837 % The format of the RegisterTIFFImage method is:
1839 % size_t RegisterTIFFImage(void)
1843 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1844 static TIFFExtendProc
1845 tag_extender = (TIFFExtendProc) NULL;
1847 static void TIFFIgnoreTags(TIFF *tiff)
1868 if (TIFFGetReadProc(tiff) != TIFFReadBlob)
1870 image=(Image *)TIFFClientdata(tiff);
1871 tags=GetImageArtifact(image,"tiff:ignore-tags");
1872 if (tags == (const char *) NULL)
1878 while ((isspace((int) ((unsigned char) *p)) != 0))
1881 (void) strtol(p,&q,10);
1888 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
1895 ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
1896 // This also sets field_bit to 0 (FIELD_IGNORE)
1897 ResetMagickMemory(ignore,0,count*sizeof(*ignore));
1900 while ((isspace((int) ((unsigned char) *p)) != 0))
1903 ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
1908 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
1911 (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
1912 ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
1915 static void TIFFTagExtender(TIFF *tiff)
1917 static const TIFFFieldInfo
1920 { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1921 (char *) "PhotoshopLayerData" },
1922 { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1923 (char *) "Microscope" }
1926 TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
1927 sizeof(*TIFFExtensions));
1928 if (tag_extender != (TIFFExtendProc) NULL)
1929 (*tag_extender)(tiff);
1930 TIFFIgnoreTags(tiff);
1934 ModuleExport size_t RegisterTIFFImage(void)
1936 #define TIFFDescription "Tagged Image File Format"
1939 version[MaxTextExtent];
1944 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1945 ActivateSemaphoreInfo(&tiff_semaphore);
1946 LockSemaphoreInfo(tiff_semaphore);
1947 if (instantiate_key == MagickFalse)
1949 if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
1950 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1951 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1952 if (tag_extender == (TIFFExtendProc) NULL)
1953 tag_extender=TIFFSetTagExtender(TIFFTagExtender);
1955 instantiate_key=MagickTrue;
1957 UnlockSemaphoreInfo(tiff_semaphore);
1959 #if defined(TIFF_VERSION)
1960 (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
1962 #if defined(MAGICKCORE_TIFF_DELEGATE)
1971 for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
1977 entry=SetMagickInfo("GROUP4");
1978 #if defined(MAGICKCORE_TIFF_DELEGATE)
1979 entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
1980 entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
1982 entry->raw=MagickTrue;
1983 entry->endian_support=MagickTrue;
1984 entry->adjoin=MagickFalse;
1985 entry->format_type=ImplicitFormatType;
1986 entry->seekable_stream=MagickTrue;
1987 entry->thread_support=NoThreadSupport;
1988 entry->description=ConstantString("Raw CCITT Group4");
1989 entry->mime_type=ConstantString("image/tiff");
1990 entry->module=ConstantString("TIFF");
1991 (void) RegisterMagickInfo(entry);
1992 entry=SetMagickInfo("PTIF");
1993 #if defined(MAGICKCORE_TIFF_DELEGATE)
1994 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1995 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1997 entry->endian_support=MagickTrue;
1998 entry->seekable_stream=MagickTrue;
1999 entry->thread_support=NoThreadSupport;
2000 entry->description=ConstantString("Pyramid encoded TIFF");
2001 entry->mime_type=ConstantString("image/tiff");
2002 entry->module=ConstantString("TIFF");
2003 (void) RegisterMagickInfo(entry);
2004 entry=SetMagickInfo("TIF");
2005 #if defined(MAGICKCORE_TIFF_DELEGATE)
2006 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2007 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2009 entry->endian_support=MagickTrue;
2010 entry->seekable_stream=MagickTrue;
2011 entry->stealth=MagickTrue;
2012 entry->thread_support=NoThreadSupport;
2013 entry->description=ConstantString(TIFFDescription);
2014 if (*version != '\0')
2015 entry->version=ConstantString(version);
2016 entry->mime_type=ConstantString("image/tiff");
2017 entry->module=ConstantString("TIFF");
2018 (void) RegisterMagickInfo(entry);
2019 entry=SetMagickInfo("TIFF");
2020 #if defined(MAGICKCORE_TIFF_DELEGATE)
2021 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2022 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2024 entry->magick=(IsImageFormatHandler *) IsTIFF;
2025 entry->endian_support=MagickTrue;
2026 entry->seekable_stream=MagickTrue;
2027 entry->thread_support=NoThreadSupport;
2028 entry->description=ConstantString(TIFFDescription);
2029 if (*version != '\0')
2030 entry->version=ConstantString(version);
2031 entry->mime_type=ConstantString("image/tiff");
2032 entry->module=ConstantString("TIFF");
2033 (void) RegisterMagickInfo(entry);
2034 entry=SetMagickInfo("TIFF64");
2035 #if defined(TIFF_VERSION_BIG)
2036 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
2037 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
2039 entry->adjoin=MagickFalse;
2040 entry->endian_support=MagickTrue;
2041 entry->seekable_stream=MagickTrue;
2042 entry->thread_support=NoThreadSupport;
2043 entry->description=ConstantString("Tagged Image File Format (64-bit)");
2044 if (*version != '\0')
2045 entry->version=ConstantString(version);
2046 entry->mime_type=ConstantString("image/tiff");
2047 entry->module=ConstantString("TIFF");
2048 (void) RegisterMagickInfo(entry);
2049 return(MagickImageCoderSignature);
2053 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2057 % U n r e g i s t e r T I F F I m a g e %
2061 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2063 % UnregisterTIFFImage() removes format registrations made by the TIFF module
2064 % from the list of supported formats.
2066 % The format of the UnregisterTIFFImage method is:
2068 % UnregisterTIFFImage(void)
2071 ModuleExport void UnregisterTIFFImage(void)
2073 (void) UnregisterMagickInfo("TIFF64");
2074 (void) UnregisterMagickInfo("TIFF");
2075 (void) UnregisterMagickInfo("TIF");
2076 (void) UnregisterMagickInfo("PTIF");
2077 if (tiff_semaphore == (SemaphoreInfo *) NULL)
2078 ActivateSemaphoreInfo(&tiff_semaphore);
2079 LockSemaphoreInfo(tiff_semaphore);
2080 if (instantiate_key != MagickFalse)
2082 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2083 if (tag_extender == (TIFFExtendProc) NULL)
2084 (void) TIFFSetTagExtender(tag_extender);
2086 if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
2087 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2088 instantiate_key=MagickFalse;
2090 UnlockSemaphoreInfo(tiff_semaphore);
2091 RelinquishSemaphoreInfo(&tiff_semaphore);
2094 #if defined(MAGICKCORE_TIFF_DELEGATE)
2096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2100 % W r i t e G R O U P 4 I m a g e %
2104 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2106 % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
2108 % The format of the WriteGROUP4Image method is:
2110 % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2111 % Image *image,ExceptionInfo *)
2113 % A description of each parameter follows:
2115 % o image_info: the image info.
2117 % o image: The image.
2119 % o exception: return any errors or warnings in this structure.
2122 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2123 Image *image,ExceptionInfo *exception)
2126 filename[MaxTextExtent];
2160 Write image as CCITT Group4 TIFF image to a temporary file.
2162 assert(image_info != (const ImageInfo *) NULL);
2163 assert(image_info->signature == MagickSignature);
2164 assert(image != (Image *) NULL);
2165 assert(image->signature == MagickSignature);
2166 if (image->debug != MagickFalse)
2167 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2168 assert(exception != (ExceptionInfo *) NULL);
2169 assert(exception->signature == MagickSignature);
2170 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2171 if (status == MagickFalse)
2173 huffman_image=CloneImage(image,0,0,MagickTrue,exception);
2174 if (huffman_image == (Image *) NULL)
2176 (void) CloseBlob(image);
2177 return(MagickFalse);
2179 huffman_image->endian=MSBEndian;
2181 unique_file=AcquireUniqueFileResource(filename);
2182 if (unique_file != -1)
2183 file=fdopen(unique_file,"wb");
2184 if ((unique_file == -1) || (file == (FILE *) NULL))
2186 ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
2188 return(MagickFalse);
2190 (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
2192 (void) SetImageType(huffman_image,BilevelType,exception);
2193 write_info=CloneImageInfo((ImageInfo *) NULL);
2194 SetImageInfoFile(write_info,file);
2195 write_info->compression=Group4Compression;
2196 write_info->type=BilevelType;
2197 (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
2198 status=WriteTIFFImage(write_info,huffman_image,exception);
2199 (void) fflush(file);
2200 write_info=DestroyImageInfo(write_info);
2201 if (status == MagickFalse)
2203 huffman_image=DestroyImage(huffman_image);
2204 (void) fclose(file);
2205 (void) RelinquishUniqueFileResource(filename);
2206 return(MagickFalse);
2208 tiff=TIFFOpen(filename,"rb");
2209 if (tiff == (TIFF *) NULL)
2211 huffman_image=DestroyImage(huffman_image);
2212 (void) fclose(file);
2213 (void) RelinquishUniqueFileResource(filename);
2214 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
2215 image_info->filename);
2216 return(MagickFalse);
2219 Allocate raw strip buffer.
2221 if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2224 huffman_image=DestroyImage(huffman_image);
2225 (void) fclose(file);
2226 (void) RelinquishUniqueFileResource(filename);
2227 return(MagickFalse);
2229 strip_size=byte_count[0];
2230 for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2231 if (byte_count[i] > strip_size)
2232 strip_size=byte_count[i];
2233 buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2235 if (buffer == (unsigned char *) NULL)
2238 huffman_image=DestroyImage(huffman_image);
2239 (void) fclose(file);
2240 (void) RelinquishUniqueFileResource(filename);
2241 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2242 image_info->filename);
2245 Compress runlength encoded to 2D Huffman pixels.
2247 for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2249 count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2250 if (WriteBlob(image,(size_t) count,buffer) != count)
2253 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2255 huffman_image=DestroyImage(huffman_image);
2256 (void) fclose(file);
2257 (void) RelinquishUniqueFileResource(filename);
2258 (void) CloseBlob(image);
2263 #if defined(MAGICKCORE_TIFF_DELEGATE)
2265 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2269 % W r i t e P T I F I m a g e %
2273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2275 % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2278 % The format of the WritePTIFImage method is:
2280 % MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2281 % Image *image,ExceptionInfo *exception)
2283 % A description of each parameter follows:
2285 % o image_info: the image info.
2287 % o image: The image.
2289 % o exception: return any errors or warnings in this structure.
2292 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2293 Image *image,ExceptionInfo *exception)
2314 Create pyramid-encoded TIFF image.
2316 images=NewImageList();
2317 for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2319 AppendImageToList(&images,CloneImage(next,0,0,MagickFalse,exception));
2320 columns=next->columns;
2322 resolution=next->resolution;
2323 while ((columns > 64) && (rows > 64))
2329 pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
2330 if (pyramid_image == (Image *) NULL)
2332 pyramid_image->resolution=resolution;
2333 AppendImageToList(&images,pyramid_image);
2336 images=GetFirstImageInList(images);
2338 Write pyramid-encoded TIFF image.
2340 write_info=CloneImageInfo(image_info);
2341 write_info->adjoin=MagickTrue;
2342 (void) CopyMagickString(write_info->magick,"TIFF",MaxTextExtent);
2343 (void) CopyMagickString(images->magick,"TIFF",MaxTextExtent);
2344 status=WriteTIFFImage(write_info,images,exception);
2345 images=DestroyImageList(images);
2346 write_info=DestroyImageInfo(write_info);
2351 #if defined(MAGICKCORE_TIFF_DELEGATE)
2353 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2356 % W r i t e T I F F I m a g e %
2360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2362 % WriteTIFFImage() writes an image in the Tagged image file format.
2364 % The format of the WriteTIFFImage method is:
2366 % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2367 % Image *image,ExceptionInfo *exception)
2369 % A description of each parameter follows:
2371 % o image_info: the image info.
2373 % o image: The image.
2375 % o exception: return any errors or warnings in this structure.
2379 typedef struct _TIFFInfo
2390 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2392 assert(tiff_info != (TIFFInfo *) NULL);
2393 if (tiff_info->scanlines != (unsigned char *) NULL)
2394 tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2395 tiff_info->scanlines);
2396 if (tiff_info->pixels != (unsigned char *) NULL)
2397 tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2401 static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
2413 image_view=AcquireAuthenticCacheView(image,exception);
2414 for (y=0; y < (ssize_t) image->rows; y++)
2422 if (status == MagickFalse)
2424 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2425 if (q == (Quantum *) NULL)
2430 for (x=0; x < (ssize_t) image->columns; x++)
2436 a=QuantumScale*GetPixela(image,q)-0.5;
2439 b=QuantumScale*GetPixelb(image,q)-0.5;
2442 SetPixela(image,QuantumRange*a,q);
2443 SetPixelb(image,QuantumRange*b,q);
2444 q+=GetPixelChannels(image);
2446 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2449 image_view=DestroyCacheView(image_view);
2453 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
2454 TIFF *tiff,TIFFInfo *tiff_info)
2466 assert(tiff_info != (TIFFInfo *) NULL);
2467 (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2468 option=GetImageOption(image_info,"tiff:tile-geometry");
2469 if (option == (const char *) NULL)
2471 flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2472 if ((flags & HeightValue) == 0)
2473 tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2474 tile_columns=(uint32) tiff_info->tile_geometry.width;
2475 tile_rows=(uint32) tiff_info->tile_geometry.height;
2476 TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2477 (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2478 (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2479 tiff_info->tile_geometry.width=tile_columns;
2480 tiff_info->tile_geometry.height=tile_rows;
2481 tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2482 tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2483 tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2484 tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2485 if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2486 (tiff_info->pixels == (unsigned char *) NULL))
2488 DestroyTIFFInfo(tiff_info);
2489 return(MagickFalse);
2494 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2495 tsample_t sample,Image *image)
2503 register unsigned char
2517 if (TIFFIsTiled(tiff) == 0)
2518 return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2520 Fill scanlines to tile height.
2522 i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2523 (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2524 (size_t) TIFFScanlineSize(tiff));
2525 if (((size_t) (row % tiff_info->tile_geometry.height) !=
2526 (tiff_info->tile_geometry.height-1)) &&
2527 (row != (ssize_t) (image->rows-1)))
2530 Write tile to TIFF image.
2533 bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
2534 tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
2535 number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2536 tiff_info->tile_geometry.width;
2537 for (i=0; i < (ssize_t) number_tiles; i++)
2539 tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2540 tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2541 for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2542 for (k=0; k < (ssize_t) tile_width; k++)
2544 if (bytes_per_pixel == 0)
2546 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2547 tiff_info->tile_geometry.width+k)/8);
2548 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2552 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2553 tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2554 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2555 for (l=0; l < bytes_per_pixel; l++)
2558 if ((i*tiff_info->tile_geometry.width) != image->columns)
2559 status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2560 tiff_info->tile_geometry.width),(uint32) ((row/
2561 tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2569 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2577 if (image->profiles == (void *) NULL)
2579 ResetImageProfileIterator(image);
2580 for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2582 profile=GetImageProfile(image,name);
2583 if (GetStringInfoLength(profile) == 0)
2585 name=GetNextImageProfile(image);
2588 #if defined(TIFFTAG_XMLPACKET)
2589 if (LocaleCompare(name,"xmp") == 0)
2590 (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2591 profile),GetStringInfoDatum(profile));
2593 #if defined(TIFFTAG_ICCPROFILE)
2594 if (LocaleCompare(name,"icc") == 0)
2595 (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2596 profile),GetStringInfoDatum(profile));
2598 if (LocaleCompare(name,"iptc") == 0)
2606 iptc_profile=CloneStringInfo(profile);
2607 length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2609 SetStringInfoLength(iptc_profile,length);
2610 if (TIFFIsByteSwapped(tiff))
2611 TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2612 (unsigned long) (length/4));
2613 (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2614 GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2615 iptc_profile=DestroyStringInfo(iptc_profile);
2617 #if defined(TIFFTAG_PHOTOSHOP)
2618 if (LocaleCompare(name,"8bim") == 0)
2619 (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2620 GetStringInfoLength(profile),GetStringInfoDatum(profile));
2622 if (LocaleCompare(name,"tiff:37724") == 0)
2623 (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
2624 GetStringInfoDatum(profile));
2625 if (LocaleCompare(name,"tiff:34118") == 0)
2626 (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
2627 GetStringInfoDatum(profile));
2628 name=GetNextImageProfile(image);
2632 static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
2637 value=GetImageArtifact(image,"tiff:document");
2638 if (value != (const char *) NULL)
2639 (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
2640 value=GetImageArtifact(image,"tiff:hostcomputer");
2641 if (value != (const char *) NULL)
2642 (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2643 value=GetImageArtifact(image,"tiff:artist");
2644 if (value != (const char *) NULL)
2645 (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2646 value=GetImageArtifact(image,"tiff:timestamp");
2647 if (value != (const char *) NULL)
2648 (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2649 value=GetImageArtifact(image,"tiff:make");
2650 if (value != (const char *) NULL)
2651 (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2652 value=GetImageArtifact(image,"tiff:model");
2653 if (value != (const char *) NULL)
2654 (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2655 value=GetImageArtifact(image,"tiff:software");
2656 if (value != (const char *) NULL)
2657 (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2658 value=GetImageArtifact(image,"tiff:copyright");
2659 if (value != (const char *) NULL)
2660 (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
2661 value=GetImageArtifact(image,"kodak-33423");
2662 if (value != (const char *) NULL)
2663 (void) TIFFSetField(tiff,33423,value);
2664 value=GetImageArtifact(image,"kodak-36867");
2665 if (value != (const char *) NULL)
2666 (void) TIFFSetField(tiff,36867,value);
2667 value=GetImageArtifact(image,"label");
2668 if (value != (const char *) NULL)
2669 (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
2670 value=GetImageArtifact(image,"comment");
2671 if (value != (const char *) NULL)
2672 (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
2675 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
2676 ExceptionInfo *exception)
2678 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
2689 Write EXIF properties.
2692 (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
2693 for (i=0; exif_info[i].tag != 0; i++)
2695 value=GetImageProperty(image,exif_info[i].property,exception);
2696 if (value == (const char *) NULL)
2698 switch (exif_info[i].type)
2702 (void) TIFFSetField(tiff,exif_info[i].tag,value);
2710 field=(uint16) StringToLong(value);
2711 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2719 field=(uint16) StringToLong(value);
2720 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2724 case TIFF_SRATIONAL:
2729 field=StringToDouble(value,(char **) NULL);
2730 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2737 /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
2744 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2745 Image *image,ExceptionInfo *exception)
2747 #if !defined(TIFFDefaultStripSize)
2748 #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
2808 assert(image_info != (const ImageInfo *) NULL);
2809 assert(image_info->signature == MagickSignature);
2810 assert(image != (Image *) NULL);
2811 assert(image->signature == MagickSignature);
2812 if (image->debug != MagickFalse)
2813 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2814 assert(exception != (ExceptionInfo *) NULL);
2815 assert(exception->signature == MagickSignature);
2816 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2817 if (status == MagickFalse)
2819 (void) MagickSetThreadValue(tiff_exception,exception);
2820 error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
2821 warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
2822 endian_type=UndefinedEndian;
2823 option=GetImageOption(image_info,"tiff:endian");
2824 if (option != (const char *) NULL)
2826 if (LocaleNCompare(option,"msb",3) == 0)
2827 endian_type=MSBEndian;
2828 if (LocaleNCompare(option,"lsb",3) == 0)
2829 endian_type=LSBEndian;;
2831 switch (endian_type)
2833 case LSBEndian: mode="wl"; break;
2834 case MSBEndian: mode="wb"; break;
2835 default: mode="w"; break;
2837 #if defined(TIFF_VERSION_BIG)
2838 if (LocaleCompare(image_info->magick,"TIFF64") == 0)
2839 switch (endian_type)
2841 case LSBEndian: mode="wl8"; break;
2842 case MSBEndian: mode="wb8"; break;
2843 default: mode="w8"; break;
2846 tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
2847 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
2849 if (tiff == (TIFF *) NULL)
2851 (void) TIFFSetWarningHandler(warning_handler);
2852 (void) TIFFSetErrorHandler(error_handler);
2853 return(MagickFalse);
2856 debug=IsEventLogging();
2861 Initialize TIFF fields.
2863 if ((image_info->type != UndefinedType) &&
2864 (image_info->type != OptimizeType))
2865 (void) SetImageType(image,image_info->type,exception);
2866 compression=UndefinedCompression;
2867 if (image_info->compression != UndefinedCompression)
2868 compression=image_info->compression;
2869 switch (compression)
2871 case FaxCompression:
2872 case Group4Compression:
2874 (void) SetImageType(image,BilevelType,exception);
2877 case JPEGCompression:
2879 (void) SetImageStorageClass(image,DirectClass,exception);
2880 (void) SetImageDepth(image,8,exception);
2886 quantum_info=AcquireQuantumInfo(image_info,image);
2887 if (quantum_info == (QuantumInfo *) NULL)
2888 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2889 if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
2890 (quantum_info->format == UndefinedQuantumFormat) &&
2891 (IsHighDynamicRangeImage(image,exception) != MagickFalse))
2893 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
2894 if (status == MagickFalse)
2895 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2897 if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
2898 (GetPreviousImageInList(image) != (Image *) NULL))
2899 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
2900 if ((image->columns != (uint32) image->columns) ||
2901 (image->rows != (uint32) image->rows))
2902 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
2903 (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
2904 (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
2905 switch (compression)
2907 case FaxCompression:
2909 compress_tag=COMPRESSION_CCITTFAX3;
2910 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2913 case Group4Compression:
2915 compress_tag=COMPRESSION_CCITTFAX4;
2916 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2919 #if defined(COMPRESSION_JBIG)
2920 case JBIG1Compression:
2922 compress_tag=COMPRESSION_JBIG;
2926 case JPEGCompression:
2928 compress_tag=COMPRESSION_JPEG;
2931 #if defined(COMPRESSION_LZMA)
2932 case LZMACompression:
2934 compress_tag=COMPRESSION_LZMA;
2938 case LZWCompression:
2940 compress_tag=COMPRESSION_LZW;
2943 case RLECompression:
2945 compress_tag=COMPRESSION_PACKBITS;
2948 case ZipCompression:
2950 compress_tag=COMPRESSION_ADOBE_DEFLATE;
2956 compress_tag=COMPRESSION_NONE;
2960 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
2961 if ((compress_tag != COMPRESSION_NONE) &&
2962 (TIFFIsCODECConfigured(compress_tag) == 0))
2964 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2965 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2966 MagickCompressOptions,(ssize_t) compression));
2967 compress_tag=COMPRESSION_NONE;
2968 compression=NoCompression;
2971 switch (compress_tag)
2973 #if defined(CCITT_SUPPORT)
2974 case COMPRESSION_CCITTFAX3:
2975 case COMPRESSION_CCITTFAX4:
2977 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
2978 case COMPRESSION_JPEG:
2980 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2981 case COMPRESSION_LZMA:
2983 #if defined(LZW_SUPPORT)
2984 case COMPRESSION_LZW:
2986 #if defined(PACKBITS_SUPPORT)
2987 case COMPRESSION_PACKBITS:
2989 #if defined(ZIP_SUPPORT)
2990 case COMPRESSION_ADOBE_DEFLATE:
2992 case COMPRESSION_NONE:
2996 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2997 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2998 MagickCompressOptions,(ssize_t) compression));
2999 compress_tag=COMPRESSION_NONE;
3000 compression=NoCompression;
3005 if (image->colorspace == CMYKColorspace)
3007 photometric=PHOTOMETRIC_SEPARATED;
3008 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
3009 (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
3014 Full color TIFF raster.
3016 if (image->colorspace == LabColorspace)
3018 photometric=PHOTOMETRIC_CIELAB;
3019 EncodeLabImage(image,exception);
3022 if (image->colorspace == YCbCrColorspace)
3024 photometric=PHOTOMETRIC_YCBCR;
3025 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
3026 (void) SetImageStorageClass(image,DirectClass,exception);
3027 (void) SetImageDepth(image,8,exception);
3030 photometric=PHOTOMETRIC_RGB;
3031 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
3032 if ((image_info->type != TrueColorType) &&
3033 (image_info->type != TrueColorMatteType))
3035 if ((image_info->type != PaletteType) &&
3036 (IsImageGray(image,exception) != MagickFalse))
3038 photometric=(uint16) (quantum_info->min_is_white !=
3039 MagickFalse ? PHOTOMETRIC_MINISWHITE :
3040 PHOTOMETRIC_MINISBLACK);
3041 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3042 if ((image_info->depth == 0) &&
3043 (image->alpha_trait != BlendPixelTrait) &&
3044 (IsImageMonochrome(image,exception) != MagickFalse))
3046 status=SetQuantumDepth(image,quantum_info,1);
3047 if (status == MagickFalse)
3048 ThrowWriterException(ResourceLimitError,
3049 "MemoryAllocationFailed");
3053 if (image->storage_class == PseudoClass)
3059 Colormapped TIFF raster.
3061 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
3062 photometric=PHOTOMETRIC_PALETTE;
3064 while ((GetQuantumRange(depth)+1) < image->colors)
3066 status=SetQuantumDepth(image,quantum_info,depth);
3067 if (status == MagickFalse)
3068 ThrowWriterException(ResourceLimitError,
3069 "MemoryAllocationFailed");
3073 if (photometric == PHOTOMETRIC_RGB)
3074 (void) TransformImageColorspace(image,sRGBColorspace,exception);
3075 switch (image->endian)
3079 endian=FILLORDER_LSB2MSB;
3084 endian=FILLORDER_MSB2LSB;
3087 case UndefinedEndian:
3090 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
3094 if ((compress_tag == COMPRESSION_CCITTFAX3) &&
3095 (photometric != PHOTOMETRIC_MINISWHITE))
3097 compress_tag=COMPRESSION_NONE;
3098 endian=FILLORDER_MSB2LSB;
3101 if ((compress_tag == COMPRESSION_CCITTFAX4) &&
3102 (photometric != PHOTOMETRIC_MINISWHITE))
3104 compress_tag=COMPRESSION_NONE;
3105 endian=FILLORDER_MSB2LSB;
3107 option=GetImageOption(image_info,"tiff:fill-order");
3108 if (option != (const char *) NULL)
3110 if (LocaleNCompare(option,"msb",3) == 0)
3111 endian=FILLORDER_MSB2LSB;
3112 if (LocaleNCompare(option,"lsb",3) == 0)
3113 endian=FILLORDER_LSB2MSB;
3115 (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
3116 (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
3117 (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
3118 if (image->alpha_trait == BlendPixelTrait)
3126 TIFF has a matte channel.
3129 sample_info[0]=EXTRASAMPLE_UNASSALPHA;
3130 option=GetImageOption(image_info,"tiff:alpha");
3131 if ((option != (const char *) NULL) &&
3132 (LocaleCompare(option,"associated") == 0))
3133 sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
3134 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
3135 &samples_per_pixel);
3136 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
3137 (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
3139 if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
3140 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
3142 (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
3143 switch (quantum_info->format)
3145 case FloatingPointQuantumFormat:
3147 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
3148 (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
3149 (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
3152 case SignedQuantumFormat:
3154 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
3157 case UnsignedQuantumFormat:
3159 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
3165 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
3166 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3167 if (photometric == PHOTOMETRIC_RGB)
3168 if ((image_info->interlace == PlaneInterlace) ||
3169 (image_info->interlace == PartitionInterlace))
3170 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
3171 rows_per_strip=TIFFDefaultStripSize(tiff,0);
3172 option=GetImageOption(image_info,"tiff:rows-per-strip");
3173 if (option != (const char *) NULL)
3174 rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
3175 switch (compress_tag)
3177 case COMPRESSION_JPEG:
3179 #if defined(JPEG_SUPPORT)
3189 rows_per_strip+=(16-(rows_per_strip % 16));
3190 if (image_info->quality != UndefinedCompressionQuality)
3191 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
3192 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
3193 if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
3198 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
3199 sampling_factor=(const char *) NULL;
3200 value=GetImageProperty(image,"jpeg:sampling-factor",exception);
3201 if (value != (char *) NULL)
3203 sampling_factor=value;
3204 if (image->debug != MagickFalse)
3205 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
3206 " Input sampling-factors=%s",sampling_factor);
3208 if (image_info->sampling_factor != (char *) NULL)
3209 sampling_factor=image_info->sampling_factor;
3210 if (sampling_factor != (const char *) NULL)
3212 flags=ParseGeometry(sampling_factor,&geometry_info);
3213 if ((flags & SigmaValue) == 0)
3214 geometry_info.sigma=geometry_info.rho;
3215 if (image->colorspace == YCbCrColorspace)
3216 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
3217 geometry_info.rho,(uint16) geometry_info.sigma);
3220 if (bits_per_sample == 12)
3221 (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
3225 case COMPRESSION_ADOBE_DEFLATE:
3227 rows_per_strip=(uint32) image->rows;
3228 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3230 if (((photometric == PHOTOMETRIC_RGB) ||
3231 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3232 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3233 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3234 (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
3235 image_info->quality == UndefinedCompressionQuality ? 7 :
3236 MagickMin((ssize_t) image_info->quality/10,9)));
3239 case COMPRESSION_CCITTFAX3:
3244 rows_per_strip=(uint32) image->rows;
3245 (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
3248 case COMPRESSION_CCITTFAX4:
3250 rows_per_strip=(uint32) image->rows;
3253 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3254 case COMPRESSION_LZMA:
3256 if (((photometric == PHOTOMETRIC_RGB) ||
3257 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3258 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3259 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3260 (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
3261 image_info->quality == UndefinedCompressionQuality ? 7 :
3262 MagickMin((ssize_t) image_info->quality/10,9)));
3266 case COMPRESSION_LZW:
3268 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3270 if (((photometric == PHOTOMETRIC_RGB) ||
3271 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3272 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3273 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3279 if (rows_per_strip < 1)
3281 if ((image->rows/rows_per_strip) >= (1UL << 15))
3282 rows_per_strip=(uint32) (image->rows >> 15);
3283 (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
3284 if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
3290 Set image resolution.
3293 if (image->units == PixelsPerInchResolution)
3295 if (image->units == PixelsPerCentimeterResolution)
3296 units=RESUNIT_CENTIMETER;
3297 (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
3298 (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
3299 (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
3300 if ((image->page.x < 0) || (image->page.y < 0))
3301 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3302 "TIFF: negative image positions unsupported","%s",image->filename);
3303 if ((image->page.x > 0) && (image->resolution.x > 0.0))
3306 Set horizontal image position.
3308 (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
3309 image->resolution.x);
3311 if ((image->page.y > 0) && (image->resolution.y > 0.0))
3314 Set vertical image position.
3316 (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
3317 image->resolution.y);
3320 if (image->chromaticity.white_point.x != 0.0)
3326 Set image chromaticity.
3328 chromaticity[0]=(float) image->chromaticity.red_primary.x;
3329 chromaticity[1]=(float) image->chromaticity.red_primary.y;
3330 chromaticity[2]=(float) image->chromaticity.green_primary.x;
3331 chromaticity[3]=(float) image->chromaticity.green_primary.y;
3332 chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3333 chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3334 (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3335 chromaticity[0]=(float) image->chromaticity.white_point.x;
3336 chromaticity[1]=(float) image->chromaticity.white_point.y;
3337 (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3339 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3340 (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3342 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3343 if (image->scene != 0)
3344 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3345 GetImageListLength(image));
3347 if (image->orientation != UndefinedOrientation)
3348 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3349 (void) TIFFSetProfiles(tiff,image);
3355 page=(uint16) scene;
3356 pages=(uint16) GetImageListLength(image);
3357 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3358 (image_info->adjoin != MagickFalse) && (pages > 1))
3359 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3360 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3362 (void) TIFFSetProperties(tiff,image,exception);
3363 DisableMSCWarning(4127)
3366 (void) TIFFSetEXIFProperties(tiff,image,exception);
3368 Write image scanlines.
3370 if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3371 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3372 quantum_info->endian=LSBEndian;
3373 pixels=GetQuantumPixels(quantum_info);
3374 tiff_info.scanline=GetQuantumPixels(quantum_info);
3375 switch (photometric)
3377 case PHOTOMETRIC_CIELAB:
3378 case PHOTOMETRIC_YCBCR:
3379 case PHOTOMETRIC_RGB:
3384 switch (image_info->interlace)
3389 quantum_type=RGBQuantum;
3390 if (image->alpha_trait == BlendPixelTrait)
3391 quantum_type=RGBAQuantum;
3392 for (y=0; y < (ssize_t) image->rows; y++)
3394 register const Quantum
3397 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3398 if (p == (const Quantum *) NULL)
3400 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3401 quantum_type,pixels,exception);
3403 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3405 if (image->previous == (Image *) NULL)
3407 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3409 if (status == MagickFalse)
3415 case PlaneInterlace:
3416 case PartitionInterlace:
3419 Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
3421 for (y=0; y < (ssize_t) image->rows; y++)
3423 register const Quantum
3426 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3427 if (p == (const Quantum *) NULL)
3429 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3430 RedQuantum,pixels,exception);
3431 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3434 if (image->previous == (Image *) NULL)
3436 status=SetImageProgress(image,SaveImageTag,100,400);
3437 if (status == MagickFalse)
3440 for (y=0; y < (ssize_t) image->rows; y++)
3442 register const Quantum
3445 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3446 if (p == (const Quantum *) NULL)
3448 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3449 GreenQuantum,pixels,exception);
3450 if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3453 if (image->previous == (Image *) NULL)
3455 status=SetImageProgress(image,SaveImageTag,200,400);
3456 if (status == MagickFalse)
3459 for (y=0; y < (ssize_t) image->rows; y++)
3461 register const Quantum
3464 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3465 if (p == (const Quantum *) NULL)
3467 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3468 BlueQuantum,pixels,exception);
3469 if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3472 if (image->previous == (Image *) NULL)
3474 status=SetImageProgress(image,SaveImageTag,300,400);
3475 if (status == MagickFalse)
3478 if (image->alpha_trait == BlendPixelTrait)
3479 for (y=0; y < (ssize_t) image->rows; y++)
3481 register const Quantum
3484 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3485 if (p == (const Quantum *) NULL)
3487 length=ExportQuantumPixels(image,(CacheView *) NULL,
3488 quantum_info,AlphaQuantum,pixels,exception);
3489 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3492 if (image->previous == (Image *) NULL)
3494 status=SetImageProgress(image,SaveImageTag,400,400);
3495 if (status == MagickFalse)
3503 case PHOTOMETRIC_SEPARATED:
3508 quantum_type=CMYKQuantum;
3509 if (image->alpha_trait == BlendPixelTrait)
3510 quantum_type=CMYKAQuantum;
3511 if (image->colorspace != CMYKColorspace)
3512 (void) TransformImageColorspace(image,CMYKColorspace,exception);
3513 for (y=0; y < (ssize_t) image->rows; y++)
3515 register const Quantum
3518 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3519 if (p == (const Quantum *) NULL)
3521 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3522 quantum_type,pixels,exception);
3523 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3525 if (image->previous == (Image *) NULL)
3527 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3529 if (status == MagickFalse)
3535 case PHOTOMETRIC_PALETTE:
3543 Colormapped TIFF image.
3545 red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3546 green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3547 blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3548 if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3549 (blue == (uint16 *) NULL))
3550 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3552 Initialize TIFF colormap.
3554 (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3555 (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3556 (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3557 for (i=0; i < (ssize_t) image->colors; i++)
3559 red[i]=ScaleQuantumToShort(image->colormap[i].red);
3560 green[i]=ScaleQuantumToShort(image->colormap[i].green);
3561 blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3563 (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3564 red=(uint16 *) RelinquishMagickMemory(red);
3565 green=(uint16 *) RelinquishMagickMemory(green);
3566 blue=(uint16 *) RelinquishMagickMemory(blue);
3571 Convert PseudoClass packets to contiguous grayscale scanlines.
3573 quantum_type=IndexQuantum;
3574 if (image->alpha_trait == BlendPixelTrait)
3576 if (photometric != PHOTOMETRIC_PALETTE)
3577 quantum_type=GrayAlphaQuantum;
3579 quantum_type=IndexAlphaQuantum;
3582 if (photometric != PHOTOMETRIC_PALETTE)
3583 quantum_type=GrayQuantum;
3584 for (y=0; y < (ssize_t) image->rows; y++)
3586 register const Quantum
3589 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3590 if (p == (const Quantum *) NULL)
3592 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3593 quantum_type,pixels,exception);
3594 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3596 if (image->previous == (Image *) NULL)
3598 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3600 if (status == MagickFalse)
3607 quantum_info=DestroyQuantumInfo(quantum_info);
3608 if (image->colorspace == LabColorspace)
3609 DecodeLabImage(image,exception);
3610 DestroyTIFFInfo(&tiff_info);
3611 DisableMSCWarning(4127)
3612 if (0 && (image_info->verbose != MagickFalse))
3614 TIFFPrintDirectory(tiff,stdout,MagickFalse);
3615 (void) TIFFWriteDirectory(tiff);
3616 image=SyncNextImageInList(image);
3617 if (image == (Image *) NULL)
3619 status=SetImageProgress(image,SaveImagesTag,scene++,
3620 GetImageListLength(image));
3621 if (status == MagickFalse)
3623 } while (image_info->adjoin != MagickFalse);
3624 (void) TIFFSetWarningHandler(warning_handler);
3625 (void) TIFFSetErrorHandler(error_handler);