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 TIFF_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)
693 for (i=0; exif_info[i].tag != 0; i++)
696 switch (exif_info[i].type)
704 if ((TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0) &&
705 (field != (char *) NULL) && (*field != '\0'))
706 (void) CopyMagickString(value,field,MaxTextExtent);
715 if (exif_info[i].variable_length != 0)
717 if (TIFFGetField(tiff,exif_info[i].tag,&sans,&field,&sans,&sans) != 0)
718 (void) FormatLocaleString(value,MaxTextExtent,"%d",field);
721 if (TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0)
722 (void) FormatLocaleString(value,MaxTextExtent,"%d",field);
731 if (TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0)
732 (void) FormatLocaleString(value,MaxTextExtent,"%d",field);
735 #if defined(TIFF_VERSION_BIG)
742 if (TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0)
743 (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
744 ((MagickOffsetType) field));
756 if (TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0)
757 (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) field);
766 if (TIFFGetField(tiff,exif_info[i].tag,&field,&sans,&sans) != 0)
767 (void) FormatLocaleString(value,MaxTextExtent,"%g",field);
774 (void) SetImageProperty(image,exif_info[i].property,value,exception);
776 TIFFSetDirectory(tiff,directory);
783 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
785 *base=(tdata_t *) GetBlobStreamData((Image *) image);
786 if (*base != (tdata_t *) NULL)
787 *size=(toff_t) GetBlobSize((Image *) image);
788 if (*base != (tdata_t *) NULL)
793 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
798 count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
799 (unsigned char *) data);
803 static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
804 tsample_t sample,ssize_t row,tdata_t scanline)
809 (void) bits_per_sample;
810 status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
814 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
816 return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
819 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
826 static void TIFFWarnings(const char *module,const char *format,va_list warning)
829 message[MaxTextExtent];
834 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
835 (void) vsnprintf(message,MaxTextExtent,format,warning);
837 (void) vsprintf(message,format,warning);
839 (void) ConcatenateMagickString(message,".",MaxTextExtent);
840 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
841 if (exception != (ExceptionInfo *) NULL)
842 (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
843 message,"`%s'",module);
846 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
851 count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
852 (unsigned char *) data);
856 #if defined(__cplusplus) || defined(c_plusplus)
860 static Image *ReadTIFFImage(const ImageInfo *image_info,
861 ExceptionInfo *exception)
865 ReadSingleSampleMethod,
948 assert(image_info != (const ImageInfo *) NULL);
949 assert(image_info->signature == MagickSignature);
950 if (image_info->debug != MagickFalse)
951 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
952 image_info->filename);
953 assert(exception != (ExceptionInfo *) NULL);
954 assert(exception->signature == MagickSignature);
955 image=AcquireImage(image_info,exception);
956 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
957 if (status == MagickFalse)
959 image=DestroyImageList(image);
960 return((Image *) NULL);
962 (void) MagickSetThreadValue(tiff_exception,exception);
963 error_handler=TIFFSetErrorHandler(TIFFErrors);
964 warning_handler=TIFFSetWarningHandler(TIFFWarnings);
965 tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
966 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
968 if (tiff == (TIFF *) NULL)
970 (void) TIFFSetWarningHandler(warning_handler);
971 (void) TIFFSetErrorHandler(error_handler);
972 image=DestroyImageList(image);
973 return((Image *) NULL);
975 debug=IsEventLogging();
977 if (image_info->number_scenes != 0)
980 Generate blank images for subimage specification (e.g. image.tif[4].
982 for (i=0; i < (ssize_t) image_info->scene; i++)
984 (void) TIFFReadDirectory(tiff);
985 AcquireNextImage(image_info,image,exception);
986 if (GetNextImageInList(image) == (Image *) NULL)
988 image=DestroyImageList(image);
989 return((Image *) NULL);
991 image=SyncNextImageInList(image);
996 DisableMSCWarning(4127)
997 if (0 && (image_info->verbose != MagickFalse))
999 TIFFPrintDirectory(tiff,stdout,MagickFalse);
1000 #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
1001 (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
1002 "lsb" : "msb",exception);
1004 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
1005 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
1006 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
1007 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGELENGTH,&height);
1008 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
1009 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace);
1010 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample);
1011 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format);
1012 if (sample_format == SAMPLEFORMAT_IEEEFP)
1013 (void) SetImageProperty(image,"quantum:format","floating-point",
1015 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value);
1016 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value);
1017 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric);
1018 switch (photometric)
1020 case PHOTOMETRIC_MINISBLACK:
1022 (void) SetImageProperty(image,"tiff:photometric","min-is-black",
1026 case PHOTOMETRIC_MINISWHITE:
1028 (void) SetImageProperty(image,"tiff:photometric","min-is-white",
1032 case PHOTOMETRIC_PALETTE:
1034 (void) SetImageProperty(image,"tiff:photometric","palette",exception);
1037 case PHOTOMETRIC_RGB:
1039 (void) SetImageProperty(image,"tiff:photometric","RGB",exception);
1042 case PHOTOMETRIC_CIELAB:
1044 (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
1047 case PHOTOMETRIC_SEPARATED:
1049 (void) SetImageProperty(image,"tiff:photometric","separated",exception);
1052 case PHOTOMETRIC_YCBCR:
1054 (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
1059 (void) SetImageProperty(image,"tiff:photometric","unknown",exception);
1063 if (image->debug != MagickFalse)
1065 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
1066 (unsigned int) width,(unsigned int) height);
1067 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
1069 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1070 "Bits per sample: %u",bits_per_sample);
1071 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1072 "Min sample value: %u",min_sample_value);
1073 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1074 "Max sample value: %u",max_sample_value);
1075 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
1076 "interpretation: %s",GetImageProperty(image,"tiff:photometric",
1079 image->columns=(size_t) width;
1080 image->rows=(size_t) height;
1081 image->depth=(size_t) bits_per_sample;
1082 if (image->debug != MagickFalse)
1083 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
1084 (double) image->depth);
1085 image->endian=MSBEndian;
1086 if (endian == FILLORDER_LSB2MSB)
1087 image->endian=LSBEndian;
1088 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1089 (photometric == PHOTOMETRIC_MINISWHITE))
1090 SetImageColorspace(image,GRAYColorspace,exception);
1091 if (photometric == PHOTOMETRIC_SEPARATED)
1092 SetImageColorspace(image,CMYKColorspace,exception);
1093 if (photometric == PHOTOMETRIC_CIELAB)
1094 SetImageColorspace(image,LabColorspace,exception);
1095 TIFFGetProfiles(tiff,image,exception);
1096 TIFFGetProperties(tiff,image,exception);
1097 option=GetImageOption(image_info,"tiff:exif-properties");
1098 if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
1099 TIFFGetEXIFProperties(tiff,image,exception);
1100 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
1101 &samples_per_pixel);
1102 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
1103 x_resolution=(float) image->resolution.x;
1104 y_resolution=(float) image->resolution.y;
1105 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution);
1106 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
1107 image->resolution.x=x_resolution;
1108 image->resolution.y=y_resolution;
1109 x_position=(float) PerceptibleReciprocal(x_resolution)*image->page.x;
1110 y_position=(float) PerceptibleReciprocal(y_resolution)*image->page.y;
1111 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
1112 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
1113 image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
1114 image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
1115 image->orientation=(OrientationType) orientation;
1116 chromaticity=(float *) NULL;
1117 (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
1118 if (chromaticity != (float *) NULL)
1120 image->chromaticity.white_point.x=chromaticity[0];
1121 image->chromaticity.white_point.y=chromaticity[1];
1123 chromaticity=(float *) NULL;
1124 (void) TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity);
1125 if (chromaticity != (float *) NULL)
1127 image->chromaticity.red_primary.x=chromaticity[0];
1128 image->chromaticity.red_primary.y=chromaticity[1];
1129 image->chromaticity.green_primary.x=chromaticity[2];
1130 image->chromaticity.green_primary.y=chromaticity[3];
1131 image->chromaticity.blue_primary.x=chromaticity[4];
1132 image->chromaticity.blue_primary.y=chromaticity[5];
1134 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
1135 if ((compress_tag != COMPRESSION_NONE) &&
1136 (TIFFIsCODECConfigured(compress_tag) == 0))
1139 ThrowReaderException(CoderError,"CompressNotSupported");
1142 switch (compress_tag)
1144 case COMPRESSION_NONE: image->compression=NoCompression; break;
1145 case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1146 case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1147 case COMPRESSION_JPEG:
1149 image->compression=JPEGCompression;
1150 #if defined(JPEG_SUPPORT)
1153 sampling_factor[MaxTextExtent];
1159 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
1160 &horizontal,&vertical);
1161 (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
1162 horizontal,vertical);
1163 (void) SetImageProperty(image,"jpeg:sampling-factor",
1164 sampling_factor,exception);
1165 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1166 "Sampling Factors: %s",sampling_factor);
1171 case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1172 #if defined(COMPRESSION_LZMA)
1173 case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1175 case COMPRESSION_LZW: image->compression=LZWCompression; break;
1176 case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1177 case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1178 default: image->compression=RLECompression; break;
1181 Allocate memory for the image and pixel buffer.
1183 quantum_info=AcquireQuantumInfo(image_info,image);
1184 if (quantum_info == (QuantumInfo *) NULL)
1187 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1189 if (sample_format == SAMPLEFORMAT_UINT)
1190 status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1191 if (sample_format == SAMPLEFORMAT_INT)
1192 status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1193 if (sample_format == SAMPLEFORMAT_IEEEFP)
1194 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1195 if (status == MagickFalse)
1197 quantum_info=DestroyQuantumInfo(quantum_info);
1199 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1202 switch (photometric)
1204 case PHOTOMETRIC_MINISBLACK:
1206 quantum_info->min_is_white=MagickFalse;
1209 case PHOTOMETRIC_MINISWHITE:
1211 quantum_info->min_is_white=MagickTrue;
1217 associated_alpha=MagickFalse;
1219 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1221 if (extra_samples == 0)
1223 if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1224 image->alpha_trait=BlendPixelTrait;
1227 for (i=0; i < extra_samples; i++)
1229 image->alpha_trait=BlendPixelTrait;
1230 if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1231 SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1233 option=GetImageOption(image_info,"tiff:alpha");
1234 if (option != (const char *) NULL)
1235 associated_alpha=LocaleCompare(option,"associated") == 0 ? MagickTrue :
1237 if (image->alpha_trait == BlendPixelTrait)
1238 (void) SetImageProperty(image,"tiff:alpha",
1239 associated_alpha != MagickFalse ? "associated" : "unassociated",
1241 if ((photometric == PHOTOMETRIC_PALETTE) &&
1242 (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1247 colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1248 if (AcquireImageColormap(image,colors,exception) == MagickFalse)
1251 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1254 if (units == RESUNIT_INCH)
1255 image->units=PixelsPerInchResolution;
1256 if (units == RESUNIT_CENTIMETER)
1257 image->units=PixelsPerCentimeterResolution;
1258 value=(unsigned short) image->scene;
1259 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages);
1261 if (image_info->ping != MagickFalse)
1263 if (image_info->number_scenes != 0)
1264 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1266 goto next_tiff_frame;
1268 method=ReadGenericMethod;
1269 if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) != 0)
1272 value[MaxTextExtent];
1274 method=ReadStripMethod;
1275 (void) FormatLocaleString(value,MaxTextExtent,"%u",
1276 (unsigned int) rows_per_strip);
1277 (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
1279 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
1280 method=ReadRGBAMethod;
1281 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
1282 method=ReadCMYKAMethod;
1283 if ((photometric != PHOTOMETRIC_RGB) &&
1284 (photometric != PHOTOMETRIC_CIELAB) &&
1285 (photometric != PHOTOMETRIC_SEPARATED))
1286 method=ReadGenericMethod;
1287 if (image->storage_class == PseudoClass)
1288 method=ReadSingleSampleMethod;
1289 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1290 (photometric == PHOTOMETRIC_MINISWHITE))
1291 method=ReadSingleSampleMethod;
1292 if ((photometric != PHOTOMETRIC_SEPARATED) &&
1293 (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1294 method=ReadGenericMethod;
1295 if (image->compression == JPEGCompression)
1296 method=ReadGenericMethod;
1297 if (TIFFIsTiled(tiff) != MagickFalse)
1298 method=ReadTileMethod;
1299 quantum_info->endian=LSBEndian;
1300 quantum_type=RGBQuantum;
1301 pixels=GetQuantumPixels(quantum_info);
1304 case ReadSingleSampleMethod:
1307 Convert TIFF image to PseudoClass MIFF image.
1309 if ((image->storage_class == PseudoClass) &&
1310 (photometric == PHOTOMETRIC_PALETTE))
1321 Initialize colormap.
1323 red_colormap=(uint16 *) NULL;
1324 green_colormap=(uint16 *) NULL;
1325 blue_colormap=(uint16 *) NULL;
1326 (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1327 &green_colormap,&blue_colormap);
1328 if ((red_colormap != (uint16 *) NULL) &&
1329 (green_colormap != (uint16 *) NULL) &&
1330 (blue_colormap != (uint16 *) NULL))
1332 range=255; /* might be old style 8-bit colormap */
1333 for (i=0; i < (ssize_t) image->colors; i++)
1334 if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1335 (blue_colormap[i] >= 256))
1340 for (i=0; i < (ssize_t) image->colors; i++)
1342 image->colormap[i].red=ClampToQuantum(((double)
1343 QuantumRange*red_colormap[i])/range);
1344 image->colormap[i].green=ClampToQuantum(((double)
1345 QuantumRange*green_colormap[i])/range);
1346 image->colormap[i].blue=ClampToQuantum(((double)
1347 QuantumRange*blue_colormap[i])/range);
1351 quantum_type=IndexQuantum;
1352 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1353 if (image->alpha_trait == BlendPixelTrait)
1355 if (image->storage_class != PseudoClass)
1357 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1359 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1363 quantum_type=IndexAlphaQuantum;
1364 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1368 if (image->storage_class != PseudoClass)
1370 quantum_type=GrayQuantum;
1371 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1373 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1374 if (status == MagickFalse)
1377 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1379 pixels=GetQuantumPixels(quantum_info);
1380 for (y=0; y < (ssize_t) image->rows; y++)
1388 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1391 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1392 if (q == (Quantum *) NULL)
1394 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1395 quantum_type,pixels,exception);
1397 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1399 if (image->previous == (Image *) NULL)
1401 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1403 if (status == MagickFalse)
1409 case ReadRGBAMethod:
1412 Convert TIFF image to DirectClass MIFF image.
1414 pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1415 quantum_type=RGBQuantum;
1416 if (image->alpha_trait == BlendPixelTrait)
1418 quantum_type=RGBAQuantum;
1419 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1421 if (image->colorspace == CMYKColorspace)
1423 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1424 quantum_type=CMYKQuantum;
1425 if (image->alpha_trait == BlendPixelTrait)
1427 quantum_type=CMYKAQuantum;
1428 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1431 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1432 if (status == MagickFalse)
1435 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1437 pixels=GetQuantumPixels(quantum_info);
1438 for (y=0; y < (ssize_t) image->rows; y++)
1446 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1449 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1450 if (q == (Quantum *) NULL)
1452 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1453 quantum_type,pixels,exception);
1454 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1456 if (image->previous == (Image *) NULL)
1458 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1460 if (status == MagickFalse)
1466 case ReadCMYKAMethod:
1469 Convert TIFF image to DirectClass MIFF image.
1471 for (i=0; i < (ssize_t) samples_per_pixel; i++)
1473 for (y=0; y < (ssize_t) image->rows; y++)
1481 status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1485 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1486 if (q == (Quantum *) NULL)
1488 if (image->colorspace != CMYKColorspace)
1491 case 0: quantum_type=RedQuantum; break;
1492 case 1: quantum_type=GreenQuantum; break;
1493 case 2: quantum_type=BlueQuantum; break;
1494 case 3: quantum_type=AlphaQuantum; break;
1495 default: quantum_type=UndefinedQuantum; break;
1500 case 0: quantum_type=CyanQuantum; break;
1501 case 1: quantum_type=MagentaQuantum; break;
1502 case 2: quantum_type=YellowQuantum; break;
1503 case 3: quantum_type=BlackQuantum; break;
1504 case 4: quantum_type=AlphaQuantum; break;
1505 default: quantum_type=UndefinedQuantum; break;
1507 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1508 quantum_type,pixels,exception);
1509 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1512 if (image->previous == (Image *) NULL)
1514 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1516 if (status == MagickFalse)
1522 case ReadStripMethod:
1528 Convert stripped TIFF image to DirectClass MIFF image.
1532 for (y=0; y < (ssize_t) image->rows; y++)
1540 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1541 if (q == (Quantum *) NULL)
1545 if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1547 i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1551 p=((uint32 *) pixels)+image->columns*i;
1552 for (x=0; x < (ssize_t) image->columns; x++)
1554 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1556 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1558 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1560 if (image->alpha_trait == BlendPixelTrait)
1561 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1564 q+=GetPixelChannels(image);
1566 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1568 if (image->previous == (Image *) NULL)
1570 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1572 if (status == MagickFalse)
1578 case ReadTileMethod:
1592 Convert tiled TIFF image to DirectClass MIFF image.
1594 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) == 0) ||
1595 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) == 0))
1598 ThrowReaderException(CoderError,"ImageIsNotTiled");
1600 (void) SetImageStorageClass(image,DirectClass,exception);
1601 number_pixels=columns*rows;
1602 tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
1603 sizeof(*tile_pixels));
1604 if (tile_pixels == (uint32 *) NULL)
1607 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1609 for (y=0; y < (ssize_t) image->rows; y+=rows)
1622 rows_remaining=image->rows-y;
1623 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1624 rows_remaining=rows;
1625 tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1627 if (tile == (Quantum *) NULL)
1629 for (x=0; x < (ssize_t) image->columns; x+=columns)
1635 if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1637 columns_remaining=image->columns-x;
1638 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1639 columns_remaining=columns;
1640 p=tile_pixels+(rows-rows_remaining)*columns;
1641 q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1643 for (row=rows_remaining; row > 0; row--)
1645 if (image->alpha_trait == BlendPixelTrait)
1646 for (column=columns_remaining; column > 0; column--)
1648 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1650 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1652 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1654 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1657 q+=GetPixelChannels(image);
1660 for (column=columns_remaining; column > 0; column--)
1662 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1664 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1666 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1669 q+=GetPixelChannels(image);
1671 p+=columns-columns_remaining;
1672 q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1675 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1677 if (image->previous == (Image *) NULL)
1679 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1681 if (status == MagickFalse)
1685 tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
1688 case ReadGenericMethod:
1701 Convert TIFF image to DirectClass MIFF image.
1703 number_pixels=(MagickSizeType) image->columns*image->rows;
1704 if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
1705 (number_pixels*sizeof(uint32))))
1708 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1710 pixel_info=AcquireVirtualMemory(image->columns,image->rows*
1712 if (pixel_info == (MemoryInfo *) NULL)
1715 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1717 pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
1718 (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
1719 (uint32) image->rows,(uint32 *) pixels,0);
1721 Convert image to DirectClass pixel packets.
1723 p=pixels+number_pixels-1;
1724 for (y=0; y < (ssize_t) image->rows; y++)
1732 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1733 if (q == (Quantum *) NULL)
1735 q+=GetPixelChannels(image)*(image->columns-1);
1736 for (x=0; x < (ssize_t) image->columns; x++)
1738 SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),
1740 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1742 SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),
1744 if (image->alpha_trait == BlendPixelTrait)
1745 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1748 q-=GetPixelChannels(image);
1750 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1752 if (image->previous == (Image *) NULL)
1754 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1756 if (status == MagickFalse)
1760 pixel_info=RelinquishVirtualMemory(pixel_info);
1764 SetQuantumImageType(image,quantum_type);
1766 quantum_info=DestroyQuantumInfo(quantum_info);
1767 if (photometric == PHOTOMETRIC_CIELAB)
1768 DecodeLabImage(image,exception);
1769 if ((photometric == PHOTOMETRIC_LOGL) ||
1770 (photometric == PHOTOMETRIC_MINISBLACK) ||
1771 (photometric == PHOTOMETRIC_MINISWHITE))
1773 image->type=GrayscaleType;
1774 if (bits_per_sample == 1)
1775 image->type=BilevelType;
1777 if (image->storage_class == PseudoClass)
1778 image->depth=GetImageDepth(image,exception);
1780 Proceed to next image.
1782 if (image_info->number_scenes != 0)
1783 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1785 status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1786 if (status == MagickTrue)
1789 Allocate next image structure.
1791 AcquireNextImage(image_info,image,exception);
1792 if (GetNextImageInList(image) == (Image *) NULL)
1794 image=DestroyImageList(image);
1795 return((Image *) NULL);
1797 image=SyncNextImageInList(image);
1798 status=SetImageProgress(image,LoadImagesTag,image->scene-1,
1800 if (status == MagickFalse)
1803 } while (status == MagickTrue);
1804 (void) TIFFSetWarningHandler(warning_handler);
1805 (void) TIFFSetErrorHandler(error_handler);
1807 return(GetFirstImageInList(image));
1812 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1816 % R e g i s t e r T I F F I m a g e %
1820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1822 % RegisterTIFFImage() adds properties for the TIFF image format to
1823 % the list of supported formats. The properties include the image format
1824 % tag, a method to read and/or write the format, whether the format
1825 % supports the saving of more than one frame to the same file or blob,
1826 % whether the format supports native in-memory I/O, and a brief
1827 % description of the format.
1829 % The format of the RegisterTIFFImage method is:
1831 % size_t RegisterTIFFImage(void)
1835 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1836 static TIFFExtendProc
1837 tag_extender = (TIFFExtendProc) NULL;
1839 static void TIFFTagExtender(TIFF *tiff)
1841 static const TIFFFieldInfo
1844 { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1845 (char *) "PhotoshopLayerData" },
1846 { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1847 (char *) "Microscope" }
1850 TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
1851 sizeof(*TIFFExtensions));
1852 if (tag_extender != (TIFFExtendProc) NULL)
1853 (*tag_extender)(tiff);
1857 ModuleExport size_t RegisterTIFFImage(void)
1859 #define TIFFDescription "Tagged Image File Format"
1862 version[MaxTextExtent];
1867 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1868 tiff_semaphore=AllocateSemaphoreInfo();
1869 LockSemaphoreInfo(tiff_semaphore);
1870 if (instantiate_key == MagickFalse)
1872 if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
1873 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1874 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1875 if (tag_extender == (TIFFExtendProc) NULL)
1876 tag_extender=TIFFSetTagExtender(TIFFTagExtender);
1878 instantiate_key=MagickTrue;
1880 UnlockSemaphoreInfo(tiff_semaphore);
1882 #if defined(TIFF_VERSION)
1883 (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
1885 #if defined(MAGICKCORE_TIFF_DELEGATE)
1894 for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
1900 entry=SetMagickInfo("GROUP4");
1901 #if defined(MAGICKCORE_TIFF_DELEGATE)
1902 entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
1903 entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
1905 entry->raw=MagickTrue;
1906 entry->endian_support=MagickTrue;
1907 entry->adjoin=MagickFalse;
1908 entry->format_type=ImplicitFormatType;
1909 entry->seekable_stream=MagickTrue;
1910 entry->thread_support=NoThreadSupport;
1911 entry->description=ConstantString("Raw CCITT Group4");
1912 entry->mime_type=ConstantString("image/tiff");
1913 entry->module=ConstantString("TIFF");
1914 (void) RegisterMagickInfo(entry);
1915 entry=SetMagickInfo("PTIF");
1916 #if defined(MAGICKCORE_TIFF_DELEGATE)
1917 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1918 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1920 entry->endian_support=MagickTrue;
1921 entry->seekable_stream=MagickTrue;
1922 entry->thread_support=NoThreadSupport;
1923 entry->description=ConstantString("Pyramid encoded TIFF");
1924 entry->mime_type=ConstantString("image/tiff");
1925 entry->module=ConstantString("TIFF");
1926 (void) RegisterMagickInfo(entry);
1927 entry=SetMagickInfo("TIF");
1928 #if defined(MAGICKCORE_TIFF_DELEGATE)
1929 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1930 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1932 entry->endian_support=MagickTrue;
1933 entry->seekable_stream=MagickTrue;
1934 entry->stealth=MagickTrue;
1935 entry->thread_support=NoThreadSupport;
1936 entry->description=ConstantString(TIFFDescription);
1937 if (*version != '\0')
1938 entry->version=ConstantString(version);
1939 entry->mime_type=ConstantString("image/tiff");
1940 entry->module=ConstantString("TIFF");
1941 (void) RegisterMagickInfo(entry);
1942 entry=SetMagickInfo("TIFF");
1943 #if defined(MAGICKCORE_TIFF_DELEGATE)
1944 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1945 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1947 entry->magick=(IsImageFormatHandler *) IsTIFF;
1948 entry->endian_support=MagickTrue;
1949 entry->seekable_stream=MagickTrue;
1950 entry->thread_support=NoThreadSupport;
1951 entry->description=ConstantString(TIFFDescription);
1952 if (*version != '\0')
1953 entry->version=ConstantString(version);
1954 entry->mime_type=ConstantString("image/tiff");
1955 entry->module=ConstantString("TIFF");
1956 (void) RegisterMagickInfo(entry);
1957 entry=SetMagickInfo("TIFF64");
1958 #if defined(TIFF_VERSION_BIG)
1959 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1960 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1962 entry->adjoin=MagickFalse;
1963 entry->endian_support=MagickTrue;
1964 entry->seekable_stream=MagickTrue;
1965 entry->thread_support=NoThreadSupport;
1966 entry->description=ConstantString("Tagged Image File Format (64-bit)");
1967 if (*version != '\0')
1968 entry->version=ConstantString(version);
1969 entry->mime_type=ConstantString("image/tiff");
1970 entry->module=ConstantString("TIFF");
1971 (void) RegisterMagickInfo(entry);
1972 return(MagickImageCoderSignature);
1976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1980 % U n r e g i s t e r T I F F I m a g e %
1984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1986 % UnregisterTIFFImage() removes format registrations made by the TIFF module
1987 % from the list of supported formats.
1989 % The format of the UnregisterTIFFImage method is:
1991 % UnregisterTIFFImage(void)
1994 ModuleExport void UnregisterTIFFImage(void)
1996 (void) UnregisterMagickInfo("TIFF64");
1997 (void) UnregisterMagickInfo("TIFF");
1998 (void) UnregisterMagickInfo("TIF");
1999 (void) UnregisterMagickInfo("PTIF");
2000 if (tiff_semaphore == (SemaphoreInfo *) NULL)
2001 tiff_semaphore=AllocateSemaphoreInfo();
2002 LockSemaphoreInfo(tiff_semaphore);
2003 if (instantiate_key != MagickFalse)
2005 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2006 if (tag_extender == (TIFFExtendProc) NULL)
2007 (void) TIFFSetTagExtender(tag_extender);
2009 if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
2010 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2011 instantiate_key=MagickFalse;
2013 UnlockSemaphoreInfo(tiff_semaphore);
2014 DestroySemaphoreInfo(&tiff_semaphore);
2017 #if defined(MAGICKCORE_TIFF_DELEGATE)
2019 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2023 % W r i t e G R O U P 4 I m a g e %
2027 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2029 % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
2031 % The format of the WriteGROUP4Image method is:
2033 % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2034 % Image *image,ExceptionInfo *)
2036 % A description of each parameter follows:
2038 % o image_info: the image info.
2040 % o image: The image.
2042 % o exception: return any errors or warnings in this structure.
2045 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2046 Image *image,ExceptionInfo *exception)
2049 filename[MaxTextExtent];
2083 Write image as CCITT Group4 TIFF image to a temporary file.
2085 assert(image_info != (const ImageInfo *) NULL);
2086 assert(image_info->signature == MagickSignature);
2087 assert(image != (Image *) NULL);
2088 assert(image->signature == MagickSignature);
2089 if (image->debug != MagickFalse)
2090 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2091 assert(exception != (ExceptionInfo *) NULL);
2092 assert(exception->signature == MagickSignature);
2093 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2094 if (status == MagickFalse)
2096 huffman_image=CloneImage(image,0,0,MagickTrue,exception);
2097 if (huffman_image == (Image *) NULL)
2099 (void) CloseBlob(image);
2100 return(MagickFalse);
2102 huffman_image->endian=MSBEndian;
2104 unique_file=AcquireUniqueFileResource(filename);
2105 if (unique_file != -1)
2106 file=fdopen(unique_file,"wb");
2107 if ((unique_file == -1) || (file == (FILE *) NULL))
2109 ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
2111 return(MagickFalse);
2113 (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
2115 (void) SetImageType(huffman_image,BilevelType,exception);
2116 write_info=CloneImageInfo((ImageInfo *) NULL);
2117 SetImageInfoFile(write_info,file);
2118 write_info->compression=Group4Compression;
2119 write_info->type=BilevelType;
2120 (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
2121 status=WriteTIFFImage(write_info,huffman_image,exception);
2122 (void) fflush(file);
2123 write_info=DestroyImageInfo(write_info);
2124 if (status == MagickFalse)
2126 huffman_image=DestroyImage(huffman_image);
2127 (void) fclose(file);
2128 (void) RelinquishUniqueFileResource(filename);
2129 return(MagickFalse);
2131 tiff=TIFFOpen(filename,"rb");
2132 if (tiff == (TIFF *) NULL)
2134 huffman_image=DestroyImage(huffman_image);
2135 (void) fclose(file);
2136 (void) RelinquishUniqueFileResource(filename);
2137 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
2138 image_info->filename);
2139 return(MagickFalse);
2142 Allocate raw strip buffer.
2144 if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2147 huffman_image=DestroyImage(huffman_image);
2148 (void) fclose(file);
2149 (void) RelinquishUniqueFileResource(filename);
2150 return(MagickFalse);
2152 strip_size=byte_count[0];
2153 for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2154 if (byte_count[i] > strip_size)
2155 strip_size=byte_count[i];
2156 buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2158 if (buffer == (unsigned char *) NULL)
2161 huffman_image=DestroyImage(huffman_image);
2162 (void) fclose(file);
2163 (void) RelinquishUniqueFileResource(filename);
2164 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2165 image_info->filename);
2168 Compress runlength encoded to 2D Huffman pixels.
2170 for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2172 count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2173 if (WriteBlob(image,(size_t) count,buffer) != count)
2176 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2178 huffman_image=DestroyImage(huffman_image);
2179 (void) fclose(file);
2180 (void) RelinquishUniqueFileResource(filename);
2181 (void) CloseBlob(image);
2186 #if defined(MAGICKCORE_TIFF_DELEGATE)
2188 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2192 % W r i t e P T I F I m a g e %
2196 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2198 % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2201 % The format of the WritePTIFImage method is:
2203 % MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2204 % Image *image,ExceptionInfo *exception)
2206 % A description of each parameter follows:
2208 % o image_info: the image info.
2210 % o image: The image.
2212 % o exception: return any errors or warnings in this structure.
2215 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2216 Image *image,ExceptionInfo *exception)
2237 Create pyramid-encoded TIFF image.
2239 images=NewImageList();
2240 for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2242 AppendImageToList(&images,CloneImage(next,0,0,MagickFalse,exception));
2243 columns=next->columns;
2245 resolution=next->resolution;
2246 while ((columns > 64) && (rows > 64))
2252 pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
2253 if (pyramid_image == (Image *) NULL)
2255 pyramid_image->resolution=resolution;
2256 AppendImageToList(&images,pyramid_image);
2259 images=GetFirstImageInList(images);
2261 Write pyramid-encoded TIFF image.
2263 write_info=CloneImageInfo(image_info);
2264 write_info->adjoin=MagickTrue;
2265 (void) CopyMagickString(write_info->magick,"TIFF",MaxTextExtent);
2266 (void) CopyMagickString(images->magick,"TIFF",MaxTextExtent);
2267 status=WriteTIFFImage(write_info,images,exception);
2268 images=DestroyImageList(images);
2269 write_info=DestroyImageInfo(write_info);
2274 #if defined(MAGICKCORE_TIFF_DELEGATE)
2276 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % W r i t e T I F F I m a g e %
2283 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2285 % WriteTIFFImage() writes an image in the Tagged image file format.
2287 % The format of the WriteTIFFImage method is:
2289 % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2290 % Image *image,ExceptionInfo *exception)
2292 % A description of each parameter follows:
2294 % o image_info: the image info.
2296 % o image: The image.
2298 % o exception: return any errors or warnings in this structure.
2302 typedef struct _TIFFInfo
2313 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2315 assert(tiff_info != (TIFFInfo *) NULL);
2316 if (tiff_info->scanlines != (unsigned char *) NULL)
2317 tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2318 tiff_info->scanlines);
2319 if (tiff_info->pixels != (unsigned char *) NULL)
2320 tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2324 static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
2336 image_view=AcquireAuthenticCacheView(image,exception);
2337 for (y=0; y < (ssize_t) image->rows; y++)
2345 if (status == MagickFalse)
2347 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2348 if (q == (Quantum *) NULL)
2353 for (x=0; x < (ssize_t) image->columns; x++)
2359 a=QuantumScale*GetPixela(image,q)-0.5;
2362 b=QuantumScale*GetPixelb(image,q)-0.5;
2365 SetPixela(image,QuantumRange*a,q);
2366 SetPixelb(image,QuantumRange*b,q);
2367 q+=GetPixelChannels(image);
2369 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2372 image_view=DestroyCacheView(image_view);
2376 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
2377 TIFF *tiff,TIFFInfo *tiff_info)
2389 assert(tiff_info != (TIFFInfo *) NULL);
2390 (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2391 option=GetImageOption(image_info,"tiff:tile-geometry");
2392 if (option == (const char *) NULL)
2394 flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2395 if ((flags & HeightValue) == 0)
2396 tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2397 tile_columns=(uint32) tiff_info->tile_geometry.width;
2398 tile_rows=(uint32) tiff_info->tile_geometry.height;
2399 TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2400 (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2401 (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2402 tiff_info->tile_geometry.width=tile_columns;
2403 tiff_info->tile_geometry.height=tile_rows;
2404 tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2405 tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2406 tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2407 tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2408 if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2409 (tiff_info->pixels == (unsigned char *) NULL))
2411 DestroyTIFFInfo(tiff_info);
2412 return(MagickFalse);
2417 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2418 tsample_t sample,Image *image)
2426 register unsigned char
2440 if (TIFFIsTiled(tiff) == 0)
2441 return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2443 Fill scanlines to tile height.
2445 i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2446 (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2447 (size_t) TIFFScanlineSize(tiff));
2448 if (((size_t) (row % tiff_info->tile_geometry.height) !=
2449 (tiff_info->tile_geometry.height-1)) &&
2450 (row != (ssize_t) (image->rows-1)))
2453 Write tile to TIFF image.
2456 bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
2457 tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
2458 number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2459 tiff_info->tile_geometry.width;
2460 for (i=0; i < (ssize_t) number_tiles; i++)
2462 tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2463 tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2464 for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2465 for (k=0; k < (ssize_t) tile_width; k++)
2467 if (bytes_per_pixel == 0)
2469 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2470 tiff_info->tile_geometry.width+k)/8);
2471 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2475 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2476 tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2477 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2478 for (l=0; l < bytes_per_pixel; l++)
2481 if ((i*tiff_info->tile_geometry.width) != image->columns)
2482 status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2483 tiff_info->tile_geometry.width),(uint32) ((row/
2484 tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2492 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2500 if (image->profiles == (void *) NULL)
2502 ResetImageProfileIterator(image);
2503 for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2505 profile=GetImageProfile(image,name);
2506 if (GetStringInfoLength(profile) == 0)
2508 name=GetNextImageProfile(image);
2511 #if defined(TIFFTAG_XMLPACKET)
2512 if (LocaleCompare(name,"xmp") == 0)
2513 (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2514 profile),GetStringInfoDatum(profile));
2516 #if defined(TIFFTAG_ICCPROFILE)
2517 if (LocaleCompare(name,"icc") == 0)
2518 (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2519 profile),GetStringInfoDatum(profile));
2521 if (LocaleCompare(name,"iptc") == 0)
2529 iptc_profile=CloneStringInfo(profile);
2530 length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2532 SetStringInfoLength(iptc_profile,length);
2533 if (TIFFIsByteSwapped(tiff))
2534 TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2535 (unsigned long) (length/4));
2536 (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2537 GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2538 iptc_profile=DestroyStringInfo(iptc_profile);
2540 #if defined(TIFFTAG_PHOTOSHOP)
2541 if (LocaleCompare(name,"8bim") == 0)
2542 (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2543 GetStringInfoLength(profile),GetStringInfoDatum(profile));
2545 if (LocaleCompare(name,"tiff:37724") == 0)
2546 (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
2547 GetStringInfoDatum(profile));
2548 if (LocaleCompare(name,"tiff:34118") == 0)
2549 (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
2550 GetStringInfoDatum(profile));
2551 name=GetNextImageProfile(image);
2555 static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
2560 (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
2561 value=GetImageProperty(image,"tiff:hostcomputer",exception);
2562 if (value != (const char *) NULL)
2563 (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2564 value=GetImageProperty(image,"tiff:artist",exception);
2565 if (value != (const char *) NULL)
2566 (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2567 value=GetImageProperty(image,"tiff:timestamp",exception);
2568 if (value != (const char *) NULL)
2569 (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2570 value=GetImageProperty(image,"tiff:make",exception);
2571 if (value != (const char *) NULL)
2572 (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2573 value=GetImageProperty(image,"tiff:model",exception);
2574 if (value != (const char *) NULL)
2575 (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2576 value=GetImageProperty(image,"tiff:software",exception);
2577 if (value != (const char *) NULL)
2578 (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2579 value=GetImageProperty(image,"tiff:copyright",exception);
2580 if (value != (const char *) NULL)
2581 (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
2582 value=GetImageProperty(image,"kodak-33423",exception);
2583 if (value != (const char *) NULL)
2584 (void) TIFFSetField(tiff,33423,value);
2585 value=GetImageProperty(image,"kodak-36867",exception);
2586 if (value != (const char *) NULL)
2587 (void) TIFFSetField(tiff,36867,value);
2588 value=GetImageProperty(image,"label",exception);
2589 if (value != (const char *) NULL)
2590 (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
2591 value=GetImageProperty(image,"comment",exception);
2592 if (value != (const char *) NULL)
2593 (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
2596 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
2597 ExceptionInfo *exception)
2599 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
2610 Write EXIF properties.
2613 (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
2614 for (i=0; exif_info[i].tag != 0; i++)
2616 value=GetImageProperty(image,exif_info[i].property,exception);
2617 if (value == (const char *) NULL)
2619 switch (exif_info[i].type)
2623 (void) TIFFSetField(tiff,exif_info[i].tag,value);
2631 field=(uint16) StringToLong(value);
2632 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2640 field=(uint16) StringToLong(value);
2641 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2645 case TIFF_SRATIONAL:
2650 field=StringToDouble(value,(char **) NULL);
2651 (void) TIFFSetField(tiff,exif_info[i].tag,field);
2658 /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
2665 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2666 Image *image,ExceptionInfo *exception)
2668 #if !defined(TIFFDefaultStripSize)
2669 #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
2729 assert(image_info != (const ImageInfo *) NULL);
2730 assert(image_info->signature == MagickSignature);
2731 assert(image != (Image *) NULL);
2732 assert(image->signature == MagickSignature);
2733 if (image->debug != MagickFalse)
2734 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2735 assert(exception != (ExceptionInfo *) NULL);
2736 assert(exception->signature == MagickSignature);
2737 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2738 if (status == MagickFalse)
2740 (void) MagickSetThreadValue(tiff_exception,exception);
2741 error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
2742 warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
2743 endian_type=UndefinedEndian;
2744 option=GetImageOption(image_info,"tiff:endian");
2745 if (option != (const char *) NULL)
2747 if (LocaleNCompare(option,"msb",3) == 0)
2748 endian_type=MSBEndian;
2749 if (LocaleNCompare(option,"lsb",3) == 0)
2750 endian_type=LSBEndian;;
2752 switch (endian_type)
2754 case LSBEndian: mode="wl"; break;
2755 case MSBEndian: mode="wb"; break;
2756 default: mode="w"; break;
2758 #if defined(TIFF_VERSION_BIG)
2759 if (LocaleCompare(image_info->magick,"TIFF64") == 0)
2760 switch (endian_type)
2762 case LSBEndian: mode="wl8"; break;
2763 case MSBEndian: mode="wb8"; break;
2764 default: mode="w8"; break;
2767 tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
2768 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
2770 if (tiff == (TIFF *) NULL)
2772 (void) TIFFSetWarningHandler(warning_handler);
2773 (void) TIFFSetErrorHandler(error_handler);
2774 return(MagickFalse);
2777 debug=IsEventLogging();
2782 Initialize TIFF fields.
2784 if ((image_info->type != UndefinedType) &&
2785 (image_info->type != OptimizeType))
2786 (void) SetImageType(image,image_info->type,exception);
2787 compression=UndefinedCompression;
2788 if (image_info->compression != UndefinedCompression)
2789 compression=image_info->compression;
2790 switch (compression)
2792 case FaxCompression:
2793 case Group4Compression:
2795 (void) SetImageType(image,BilevelType,exception);
2798 case JPEGCompression:
2800 (void) SetImageStorageClass(image,DirectClass,exception);
2801 (void) SetImageDepth(image,8,exception);
2807 quantum_info=AcquireQuantumInfo(image_info,image);
2808 if (quantum_info == (QuantumInfo *) NULL)
2809 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2810 if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
2811 (quantum_info->format == UndefinedQuantumFormat) &&
2812 (IsHighDynamicRangeImage(image,exception) != MagickFalse))
2814 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
2815 if (status == MagickFalse)
2816 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2818 if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
2819 (GetPreviousImageInList(image) != (Image *) NULL))
2820 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
2821 if ((image->columns != (uint32) image->columns) ||
2822 (image->rows != (uint32) image->rows))
2823 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
2824 (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
2825 (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
2826 switch (compression)
2828 case FaxCompression:
2830 compress_tag=COMPRESSION_CCITTFAX3;
2831 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2834 case Group4Compression:
2836 compress_tag=COMPRESSION_CCITTFAX4;
2837 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2840 #if defined(COMPRESSION_JBIG)
2841 case JBIG1Compression:
2843 compress_tag=COMPRESSION_JBIG;
2847 case JPEGCompression:
2849 compress_tag=COMPRESSION_JPEG;
2852 #if defined(COMPRESSION_LZMA)
2853 case LZMACompression:
2855 compress_tag=COMPRESSION_LZMA;
2859 case LZWCompression:
2861 compress_tag=COMPRESSION_LZW;
2864 case RLECompression:
2866 compress_tag=COMPRESSION_PACKBITS;
2869 case ZipCompression:
2871 compress_tag=COMPRESSION_ADOBE_DEFLATE;
2877 compress_tag=COMPRESSION_NONE;
2881 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
2882 if ((compress_tag != COMPRESSION_NONE) &&
2883 (TIFFIsCODECConfigured(compress_tag) == 0))
2885 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2886 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2887 MagickCompressOptions,(ssize_t) compression));
2888 compress_tag=COMPRESSION_NONE;
2889 compression=NoCompression;
2892 switch (compress_tag)
2894 #if defined(CCITT_SUPPORT)
2895 case COMPRESSION_CCITTFAX3:
2896 case COMPRESSION_CCITTFAX4:
2898 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
2899 case COMPRESSION_JPEG:
2901 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2902 case COMPRESSION_LZMA:
2904 #if defined(LZW_SUPPORT)
2905 case COMPRESSION_LZW:
2907 #if defined(PACKBITS_SUPPORT)
2908 case COMPRESSION_PACKBITS:
2910 #if defined(ZIP_SUPPORT)
2911 case COMPRESSION_ADOBE_DEFLATE:
2913 case COMPRESSION_NONE:
2917 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2918 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2919 MagickCompressOptions,(ssize_t) compression));
2920 compress_tag=COMPRESSION_NONE;
2921 compression=NoCompression;
2926 if (image->colorspace == CMYKColorspace)
2928 photometric=PHOTOMETRIC_SEPARATED;
2929 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
2930 (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
2935 Full color TIFF raster.
2937 if (image->colorspace == LabColorspace)
2939 photometric=PHOTOMETRIC_CIELAB;
2940 EncodeLabImage(image,exception);
2943 if (image->colorspace == YCbCrColorspace)
2945 photometric=PHOTOMETRIC_YCBCR;
2946 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
2947 (void) SetImageStorageClass(image,DirectClass,exception);
2948 (void) SetImageDepth(image,8,exception);
2951 photometric=PHOTOMETRIC_RGB;
2952 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
2953 if ((image_info->type != TrueColorType) &&
2954 (image_info->type != TrueColorMatteType))
2956 if ((image_info->type != PaletteType) &&
2957 (IsImageGray(image,exception) != MagickFalse))
2959 photometric=(uint16) (quantum_info->min_is_white !=
2960 MagickFalse ? PHOTOMETRIC_MINISWHITE :
2961 PHOTOMETRIC_MINISBLACK);
2962 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2963 if ((image_info->depth == 0) &&
2964 (image->alpha_trait != BlendPixelTrait) &&
2965 (IsImageMonochrome(image,exception) != MagickFalse))
2967 status=SetQuantumDepth(image,quantum_info,1);
2968 if (status == MagickFalse)
2969 ThrowWriterException(ResourceLimitError,
2970 "MemoryAllocationFailed");
2974 if (image->storage_class == PseudoClass)
2980 Colormapped TIFF raster.
2982 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2983 photometric=PHOTOMETRIC_PALETTE;
2985 while ((GetQuantumRange(depth)+1) < image->colors)
2987 status=SetQuantumDepth(image,quantum_info,depth);
2988 if (status == MagickFalse)
2989 ThrowWriterException(ResourceLimitError,
2990 "MemoryAllocationFailed");
2994 if ((photometric == PHOTOMETRIC_RGB) &&
2995 (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
2996 (void) TransformImageColorspace(image,sRGBColorspace,exception);
2997 switch (image->endian)
3001 endian=FILLORDER_LSB2MSB;
3006 endian=FILLORDER_MSB2LSB;
3009 case UndefinedEndian:
3012 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
3016 if ((compress_tag == COMPRESSION_CCITTFAX3) &&
3017 (photometric != PHOTOMETRIC_MINISWHITE))
3019 compress_tag=COMPRESSION_NONE;
3020 endian=FILLORDER_MSB2LSB;
3023 if ((compress_tag == COMPRESSION_CCITTFAX4) &&
3024 (photometric != PHOTOMETRIC_MINISWHITE))
3026 compress_tag=COMPRESSION_NONE;
3027 endian=FILLORDER_MSB2LSB;
3029 option=GetImageOption(image_info,"tiff:fill-order");
3030 if (option != (const char *) NULL)
3032 if (LocaleNCompare(option,"msb",3) == 0)
3033 endian=FILLORDER_MSB2LSB;
3034 if (LocaleNCompare(option,"lsb",3) == 0)
3035 endian=FILLORDER_LSB2MSB;
3037 (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
3038 (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
3039 (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
3040 if (image->alpha_trait == BlendPixelTrait)
3048 TIFF has a matte channel.
3051 sample_info[0]=EXTRASAMPLE_UNASSALPHA;
3052 option=GetImageOption(image_info,"tiff:alpha");
3053 if ((option != (const char *) NULL) &&
3054 (LocaleCompare(option,"associated") == 0))
3055 sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
3056 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
3057 &samples_per_pixel);
3058 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
3059 (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
3061 if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
3062 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
3064 (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
3065 switch (quantum_info->format)
3067 case FloatingPointQuantumFormat:
3069 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
3070 (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
3071 (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
3074 case SignedQuantumFormat:
3076 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
3079 case UnsignedQuantumFormat:
3081 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
3087 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
3088 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3089 if (photometric == PHOTOMETRIC_RGB)
3090 if ((image_info->interlace == PlaneInterlace) ||
3091 (image_info->interlace == PartitionInterlace))
3092 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
3093 rows_per_strip=TIFFDefaultStripSize(tiff,0);
3094 option=GetImageOption(image_info,"tiff:rows-per-strip");
3095 if (option != (const char *) NULL)
3096 rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
3097 switch (compress_tag)
3099 case COMPRESSION_JPEG:
3101 #if defined(JPEG_SUPPORT)
3111 rows_per_strip+=(16-(rows_per_strip % 16));
3112 if (image_info->quality != UndefinedCompressionQuality)
3113 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
3114 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
3115 if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
3120 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
3121 sampling_factor=(const char *) NULL;
3122 value=GetImageProperty(image,"jpeg:sampling-factor",exception);
3123 if (value != (char *) NULL)
3125 sampling_factor=value;
3126 if (image->debug != MagickFalse)
3127 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
3128 " Input sampling-factors=%s",sampling_factor);
3130 if (image_info->sampling_factor != (char *) NULL)
3131 sampling_factor=image_info->sampling_factor;
3132 if (sampling_factor != (const char *) NULL)
3134 flags=ParseGeometry(sampling_factor,&geometry_info);
3135 if ((flags & SigmaValue) == 0)
3136 geometry_info.sigma=geometry_info.rho;
3137 if (image->colorspace == YCbCrColorspace)
3138 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
3139 geometry_info.rho,(uint16) geometry_info.sigma);
3142 if (bits_per_sample == 12)
3143 (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
3147 case COMPRESSION_ADOBE_DEFLATE:
3149 rows_per_strip=(uint32) image->rows;
3150 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3152 if (((photometric == PHOTOMETRIC_RGB) ||
3153 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3154 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3155 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3156 (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
3157 image_info->quality == UndefinedCompressionQuality ? 7 :
3158 MagickMin((ssize_t) image_info->quality/10,9)));
3161 case COMPRESSION_CCITTFAX3:
3166 rows_per_strip=(uint32) image->rows;
3167 (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
3170 case COMPRESSION_CCITTFAX4:
3172 rows_per_strip=(uint32) image->rows;
3175 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3176 case COMPRESSION_LZMA:
3178 if (((photometric == PHOTOMETRIC_RGB) ||
3179 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3180 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3181 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3182 (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
3183 image_info->quality == UndefinedCompressionQuality ? 7 :
3184 MagickMin((ssize_t) image_info->quality/10,9)));
3188 case COMPRESSION_LZW:
3190 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3192 if (((photometric == PHOTOMETRIC_RGB) ||
3193 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3194 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3195 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3201 if (rows_per_strip < 1)
3203 if ((image->rows/rows_per_strip) >= (1UL << 15))
3204 rows_per_strip=(image->rows >> 15);
3205 (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
3206 if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
3212 Set image resolution.
3215 if (image->units == PixelsPerInchResolution)
3217 if (image->units == PixelsPerCentimeterResolution)
3218 units=RESUNIT_CENTIMETER;
3219 (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
3220 (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
3221 (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
3222 if ((image->page.x < 0) || (image->page.y < 0))
3223 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3224 "TIFF: negative image positions unsupported","%s",image->filename);
3225 if ((image->page.x > 0) && (image->resolution.x > 0.0))
3228 Set horizontal image position.
3230 (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
3231 image->resolution.x);
3233 if ((image->page.y > 0) && (image->resolution.y > 0.0))
3236 Set vertical image position.
3238 (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
3239 image->resolution.y);
3242 if (image->chromaticity.white_point.x != 0.0)
3248 Set image chromaticity.
3250 chromaticity[0]=(float) image->chromaticity.red_primary.x;
3251 chromaticity[1]=(float) image->chromaticity.red_primary.y;
3252 chromaticity[2]=(float) image->chromaticity.green_primary.x;
3253 chromaticity[3]=(float) image->chromaticity.green_primary.y;
3254 chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3255 chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3256 (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3257 chromaticity[0]=(float) image->chromaticity.white_point.x;
3258 chromaticity[1]=(float) image->chromaticity.white_point.y;
3259 (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3261 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3262 (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3264 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3265 if (image->scene != 0)
3266 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3267 GetImageListLength(image));
3269 if (image->orientation != UndefinedOrientation)
3270 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3271 (void) TIFFSetProfiles(tiff,image);
3277 page=(uint16) scene;
3278 pages=(uint16) GetImageListLength(image);
3279 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3280 (image_info->adjoin != MagickFalse) && (pages > 1))
3281 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3282 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3284 (void) TIFFSetProperties(tiff,image,exception);
3285 DisableMSCWarning(4127)
3288 (void) TIFFSetEXIFProperties(tiff,image,exception);
3290 Write image scanlines.
3292 if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3293 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3294 quantum_info->endian=LSBEndian;
3295 pixels=GetQuantumPixels(quantum_info);
3296 tiff_info.scanline=GetQuantumPixels(quantum_info);
3297 switch (photometric)
3299 case PHOTOMETRIC_CIELAB:
3300 case PHOTOMETRIC_YCBCR:
3301 case PHOTOMETRIC_RGB:
3306 switch (image_info->interlace)
3311 quantum_type=RGBQuantum;
3312 if (image->alpha_trait == BlendPixelTrait)
3313 quantum_type=RGBAQuantum;
3314 for (y=0; y < (ssize_t) image->rows; y++)
3316 register const Quantum
3319 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3320 if (p == (const Quantum *) NULL)
3322 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3323 quantum_type,pixels,exception);
3325 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3327 if (image->previous == (Image *) NULL)
3329 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3331 if (status == MagickFalse)
3337 case PlaneInterlace:
3338 case PartitionInterlace:
3341 Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
3343 for (y=0; y < (ssize_t) image->rows; y++)
3345 register const Quantum
3348 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3349 if (p == (const Quantum *) NULL)
3351 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3352 RedQuantum,pixels,exception);
3353 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3356 if (image->previous == (Image *) NULL)
3358 status=SetImageProgress(image,SaveImageTag,100,400);
3359 if (status == MagickFalse)
3362 for (y=0; y < (ssize_t) image->rows; y++)
3364 register const Quantum
3367 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3368 if (p == (const Quantum *) NULL)
3370 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3371 GreenQuantum,pixels,exception);
3372 if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3375 if (image->previous == (Image *) NULL)
3377 status=SetImageProgress(image,SaveImageTag,200,400);
3378 if (status == MagickFalse)
3381 for (y=0; y < (ssize_t) image->rows; y++)
3383 register const Quantum
3386 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3387 if (p == (const Quantum *) NULL)
3389 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3390 BlueQuantum,pixels,exception);
3391 if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3394 if (image->previous == (Image *) NULL)
3396 status=SetImageProgress(image,SaveImageTag,300,400);
3397 if (status == MagickFalse)
3400 if (image->alpha_trait == BlendPixelTrait)
3401 for (y=0; y < (ssize_t) image->rows; y++)
3403 register const Quantum
3406 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3407 if (p == (const Quantum *) NULL)
3409 length=ExportQuantumPixels(image,(CacheView *) NULL,
3410 quantum_info,AlphaQuantum,pixels,exception);
3411 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3414 if (image->previous == (Image *) NULL)
3416 status=SetImageProgress(image,SaveImageTag,400,400);
3417 if (status == MagickFalse)
3425 case PHOTOMETRIC_SEPARATED:
3430 quantum_type=CMYKQuantum;
3431 if (image->alpha_trait == BlendPixelTrait)
3432 quantum_type=CMYKAQuantum;
3433 if (image->colorspace != CMYKColorspace)
3434 (void) TransformImageColorspace(image,CMYKColorspace,exception);
3435 for (y=0; y < (ssize_t) image->rows; y++)
3437 register const Quantum
3440 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3441 if (p == (const Quantum *) NULL)
3443 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3444 quantum_type,pixels,exception);
3445 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3447 if (image->previous == (Image *) NULL)
3449 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3451 if (status == MagickFalse)
3457 case PHOTOMETRIC_PALETTE:
3465 Colormapped TIFF image.
3467 red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3468 green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3469 blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3470 if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3471 (blue == (uint16 *) NULL))
3472 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3474 Initialize TIFF colormap.
3476 (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3477 (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3478 (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3479 for (i=0; i < (ssize_t) image->colors; i++)
3481 red[i]=ScaleQuantumToShort(image->colormap[i].red);
3482 green[i]=ScaleQuantumToShort(image->colormap[i].green);
3483 blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3485 (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3486 red=(uint16 *) RelinquishMagickMemory(red);
3487 green=(uint16 *) RelinquishMagickMemory(green);
3488 blue=(uint16 *) RelinquishMagickMemory(blue);
3493 Convert PseudoClass packets to contiguous grayscale scanlines.
3495 quantum_type=IndexQuantum;
3496 if (image->alpha_trait == BlendPixelTrait)
3498 if (photometric != PHOTOMETRIC_PALETTE)
3499 quantum_type=GrayAlphaQuantum;
3501 quantum_type=IndexAlphaQuantum;
3504 if (photometric != PHOTOMETRIC_PALETTE)
3505 quantum_type=GrayQuantum;
3506 for (y=0; y < (ssize_t) image->rows; y++)
3508 register const Quantum
3511 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3512 if (p == (const Quantum *) NULL)
3514 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3515 quantum_type,pixels,exception);
3516 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3518 if (image->previous == (Image *) NULL)
3520 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3522 if (status == MagickFalse)
3529 quantum_info=DestroyQuantumInfo(quantum_info);
3530 if (image->colorspace == LabColorspace)
3531 DecodeLabImage(image,exception);
3532 DestroyTIFFInfo(&tiff_info);
3533 DisableMSCWarning(4127)
3534 if (0 && (image_info->verbose == MagickTrue))
3536 TIFFPrintDirectory(tiff,stdout,MagickFalse);
3537 (void) TIFFWriteDirectory(tiff);
3538 image=SyncNextImageInList(image);
3539 if (image == (Image *) NULL)
3541 status=SetImageProgress(image,SaveImagesTag,scene++,
3542 GetImageListLength(image));
3543 if (status == MagickFalse)
3545 } while (image_info->adjoin != MagickFalse);
3546 (void) TIFFSetWarningHandler(warning_handler);
3547 (void) TIFFSetErrorHandler(error_handler);