2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % TTTTT IIIII FFFFF FFFFF %
13 % Read/Write TIFF Image Format %
20 % Copyright 1999-2013 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_PIXELXDIMENSION, TIFF_SHORT, 0, "exif:PixelXDimension" },
151 { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
152 { EXIFTAG_PIXELYDIMENSION, TIFF_SHORT, 0, "exif:PixelYDimension" },
153 { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
154 { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
155 { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
156 { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
157 { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
158 { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
159 { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
160 { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
161 { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
162 { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
163 { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
164 { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
165 { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
166 { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
167 { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
168 { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
169 { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
170 { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
171 { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
172 { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
173 { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
174 { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
175 { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
176 { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
177 { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
178 { 0, 0, 0, (char *) NULL }
181 #endif /* MAGICKCORE_TIFF_DELEGATE */
186 static MagickThreadKey
190 *tiff_semaphore = (SemaphoreInfo *) NULL;
192 static volatile MagickBooleanType
193 instantiate_key = MagickFalse;
196 Forward declarations.
198 #if defined(MAGICKCORE_TIFF_DELEGATE)
200 ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
202 static MagickBooleanType
203 WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
204 WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
205 WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
209 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
217 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
219 % IsTIFF() returns MagickTrue if the image format type, identified by the
220 % magick string, is TIFF.
222 % The format of the IsTIFF method is:
224 % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
226 % A description of each parameter follows:
228 % o magick: compare image format pattern against these bytes.
230 % o length: Specifies the length of the magick string.
233 static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
237 if (memcmp(magick,"\115\115\000\052",4) == 0)
239 if (memcmp(magick,"\111\111\052\000",4) == 0)
241 #if defined(TIFF_VERSION_BIG)
244 if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
246 if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
252 #if defined(MAGICKCORE_TIFF_DELEGATE)
254 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
258 % R e a d G R O U P 4 I m a g e %
262 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
264 % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
265 % allocates the memory necessary for the new Image structure and returns a
266 % pointer to the new image.
268 % The format of the ReadGROUP4Image method is:
270 % Image *ReadGROUP4Image(const ImageInfo *image_info,
271 % ExceptionInfo *exception)
273 % A description of each parameter follows:
275 % o image_info: the image info.
277 % o exception: return any errors or warnings in this structure.
281 static inline size_t WriteLSBLong(FILE *file,const size_t value)
286 buffer[0]=(unsigned char) value;
287 buffer[1]=(unsigned char) (value >> 8);
288 buffer[2]=(unsigned char) (value >> 16);
289 buffer[3]=(unsigned char) (value >> 24);
290 return(fwrite(buffer,1,4,file));
293 static Image *ReadGROUP4Image(const ImageInfo *image_info,
294 ExceptionInfo *exception)
297 filename[MaxTextExtent];
325 assert(image_info != (const ImageInfo *) NULL);
326 assert(image_info->signature == MagickSignature);
327 if (image_info->debug != MagickFalse)
328 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
329 image_info->filename);
330 assert(exception != (ExceptionInfo *) NULL);
331 assert(exception->signature == MagickSignature);
332 image=AcquireImage(image_info,exception);
333 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
334 if (status == MagickFalse)
336 image=DestroyImageList(image);
337 return((Image *) NULL);
340 Write raw CCITT Group 4 wrapped as a TIFF image file.
343 unique_file=AcquireUniqueFileResource(filename);
344 if (unique_file != -1)
345 file=fdopen(unique_file,"wb");
346 if ((unique_file == -1) || (file == (FILE *) NULL))
347 ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
348 length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
349 length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
350 length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
351 length=WriteLSBLong(file,image->columns);
352 length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
353 length=WriteLSBLong(file,image->rows);
354 length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
355 length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
356 length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
357 length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
358 strip_offset=10+(12*14)+4+8;
359 length=WriteLSBLong(file,(size_t) strip_offset);
360 length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
361 length=WriteLSBLong(file,(size_t) image_info->orientation);
362 length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
363 length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
364 length=WriteLSBLong(file,image->rows);
365 length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
366 offset=(ssize_t) ftell(file)-4;
367 length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
368 length=WriteLSBLong(file,(size_t) (strip_offset-8));
369 length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
370 length=WriteLSBLong(file,(size_t) (strip_offset-8));
371 length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
372 length=fwrite("\000\000\000\000",1,4,file);
373 length=WriteLSBLong(file,(long) image->resolution.x);
374 length=WriteLSBLong(file,1);
375 for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
376 (void) fputc(c,file);
377 offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
378 length=WriteLSBLong(file,(unsigned int) length);
380 (void) CloseBlob(image);
381 image=DestroyImage(image);
385 read_info=CloneImageInfo((ImageInfo *) NULL);
386 (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
387 image=ReadTIFFImage(read_info,exception);
388 read_info=DestroyImageInfo(read_info);
389 if (image != (Image *) NULL)
391 (void) CopyMagickString(image->filename,image_info->filename,
393 (void) CopyMagickString(image->magick_filename,image_info->filename,
395 (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
397 (void) RelinquishUniqueFileResource(filename);
402 #if defined(MAGICKCORE_TIFF_DELEGATE)
404 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
408 % R e a d T I F F I m a g e %
412 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
414 % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
415 % memory necessary for the new Image structure and returns a pointer to the
418 % The format of the ReadTIFFImage method is:
420 % Image *ReadTIFFImage(const ImageInfo *image_info,
421 % ExceptionInfo *exception)
423 % A description of each parameter follows:
425 % o image_info: the image info.
427 % o exception: return any errors or warnings in this structure.
431 static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
443 image_view=AcquireAuthenticCacheView(image,exception);
444 for (y=0; y < (ssize_t) image->rows; y++)
452 if (status == MagickFalse)
454 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
455 if (q == (Quantum *) NULL)
460 for (x=0; x < (ssize_t) image->columns; x++)
466 a=QuantumScale*GetPixela(image,q)+0.5;
469 b=QuantumScale*GetPixelb(image,q)+0.5;
472 SetPixela(image,QuantumRange*a,q);
473 SetPixelb(image,QuantumRange*b,q);
474 q+=GetPixelChannels(image);
476 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
479 image_view=DestroyCacheView(image_view);
483 static inline size_t MagickMax(const size_t x,const size_t y)
490 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
497 static MagickBooleanType ReadProfile(Image *image,const char *name,
498 unsigned char *datum,ssize_t length,ExceptionInfo *exception)
512 if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"xmp") != 0))
514 for (i=0; i < (length-4); i+=2)
515 if (LocaleNCompare((char *) (datum+i),"8BIM",4) == 0)
524 profile=BlobToStringInfo(datum+i,(size_t) length);
525 if (profile == (StringInfo *) NULL)
526 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
528 status=SetImageProfile(image,name,profile,exception);
529 profile=DestroyStringInfo(profile);
530 if (status == MagickFalse)
531 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
536 #if defined(__cplusplus) || defined(c_plusplus)
540 static int TIFFCloseBlob(thandle_t image)
542 (void) CloseBlob((Image *) image);
546 static void TIFFErrors(const char *module,const char *format,va_list error)
549 message[MaxTextExtent];
554 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
555 (void) vsnprintf(message,MaxTextExtent,format,error);
557 (void) vsprintf(message,format,error);
559 (void) ConcatenateMagickString(message,".",MaxTextExtent);
560 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
561 if (exception != (ExceptionInfo *) NULL)
562 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
566 static toff_t TIFFGetBlobSize(thandle_t image)
568 return((toff_t) GetBlobSize((Image *) image));
571 static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
579 #if defined(TIFFTAG_ICCPROFILE)
581 if (TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1)
582 (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
584 #if defined(TIFFTAG_PHOTOSHOP)
586 if (TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1)
587 (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
589 #if defined(TIFFTAG_RICHTIFFIPTC)
591 if (TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1)
593 if (TIFFIsByteSwapped(tiff) != 0)
594 TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
595 (void) ReadProfile(image,"iptc",profile,4L*length,exception);
598 #if defined(TIFFTAG_XMLPACKET)
600 if (TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1)
601 (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
604 if (TIFFGetField(tiff,37724,&length,&profile) == 1)
605 (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
606 if (TIFFGetField(tiff,34118,&length,&profile) == 1)
607 (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,exception);
610 static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
613 message[MaxTextExtent],
619 if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
620 (void) SetImageProperty(image,"tiff:artist",text,exception);
621 if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
622 (void) SetImageProperty(image,"tiff:copyright",text,exception);
623 if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
624 (void) SetImageProperty(image,"tiff:timestamp",text,exception);
625 if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
626 (void) SetImageProperty(image,"tiff:document",text,exception);
627 if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
628 (void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
629 if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
630 (void) SetImageProperty(image,"comment",text,exception);
631 if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
632 (void) SetImageProperty(image,"tiff:make",text,exception);
633 if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
634 (void) SetImageProperty(image,"tiff:model",text,exception);
635 if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
637 if (count >= MaxTextExtent)
638 count=MaxTextExtent-1;
639 (void) CopyMagickString(message,text,count+1);
640 (void) SetImageProperty(image,"tiff:image-id",message,exception);
642 if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
643 (void) SetImageProperty(image,"label",text,exception);
644 if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
645 (void) SetImageProperty(image,"tiff:software",text,exception);
646 if (TIFFGetField(tiff,33423,&count,&text) == 1)
648 if (count >= MaxTextExtent)
649 count=MaxTextExtent-1;
650 (void) CopyMagickString(message,text,count+1);
651 (void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
653 if (TIFFGetField(tiff,36867,&count,&text) == 1)
655 if (count >= MaxTextExtent)
656 count=MaxTextExtent-1;
657 (void) CopyMagickString(message,text,count+1);
658 (void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
662 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
663 ExceptionInfo *exception)
665 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
667 value[MaxTextExtent];
675 #if defined(TIFF_VERSION_BIG)
686 Read EXIF properties.
689 if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) == 0)
691 directory=TIFFCurrentDirectory(tiff);
692 if (TIFFReadEXIFDirectory(tiff,offset) == 0)
695 for (i=0; exif_info[i].tag != 0; i++)
698 switch (exif_info[i].type)
706 if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) != 0) &&
707 (ascii != (char *) NULL) && (*ascii != '\0'))
708 (void) CopyMagickString(value,ascii,MaxTextExtent);
716 if (exif_info[i].variable_length != 0)
724 if (TIFFGetField(tiff,exif_info[i].tag,&count,&shorty,&sans) != 0)
725 (void) FormatLocaleString(value,MaxTextExtent,"%d",(int)
726 (*(uint16 *) shorty));
729 if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) != 0)
730 (void) FormatLocaleString(value,MaxTextExtent,"%d",(int) shorty);
738 if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) != 0)
739 (void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
742 #if defined(TIFF_VERSION_BIG)
748 if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) != 0)
749 (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
750 ((MagickOffsetType) longy));
762 if (TIFFGetField(tiff,exif_info[i].tag,&rational,&sans,&sans) != 0)
763 (void) FormatLocaleString(value,MaxTextExtent,"%g",rational[0]);
770 (void) SetImageProperty(image,exif_info[i].property,value,exception);
772 TIFFSetDirectory(tiff,directory);
779 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
781 *base=(tdata_t *) GetBlobStreamData((Image *) image);
782 if (*base != (tdata_t *) NULL)
783 *size=(toff_t) GetBlobSize((Image *) image);
784 if (*base != (tdata_t *) NULL)
789 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
794 count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
795 (unsigned char *) data);
799 static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
800 tsample_t sample,ssize_t row,tdata_t scanline)
805 (void) bits_per_sample;
806 status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
810 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
812 return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
815 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
822 static void TIFFWarnings(const char *module,const char *format,va_list warning)
825 message[MaxTextExtent];
830 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
831 (void) vsnprintf(message,MaxTextExtent,format,warning);
833 (void) vsprintf(message,format,warning);
835 (void) ConcatenateMagickString(message,".",MaxTextExtent);
836 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
837 if (exception != (ExceptionInfo *) NULL)
838 (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
839 message,"`%s'",module);
842 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
847 count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
848 (unsigned char *) data);
852 #if defined(__cplusplus) || defined(c_plusplus)
856 static Image *ReadTIFFImage(const ImageInfo *image_info,
857 ExceptionInfo *exception)
861 ReadSingleSampleMethod,
944 assert(image_info != (const ImageInfo *) NULL);
945 assert(image_info->signature == MagickSignature);
946 if (image_info->debug != MagickFalse)
947 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
948 image_info->filename);
949 assert(exception != (ExceptionInfo *) NULL);
950 assert(exception->signature == MagickSignature);
951 image=AcquireImage(image_info,exception);
952 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
953 if (status == MagickFalse)
955 image=DestroyImageList(image);
956 return((Image *) NULL);
958 (void) MagickSetThreadValue(tiff_exception,exception);
959 error_handler=TIFFSetErrorHandler(TIFFErrors);
960 warning_handler=TIFFSetWarningHandler(TIFFWarnings);
961 tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
962 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
964 if (tiff == (TIFF *) NULL)
966 (void) TIFFSetWarningHandler(warning_handler);
967 (void) TIFFSetErrorHandler(error_handler);
968 image=DestroyImageList(image);
969 return((Image *) NULL);
971 debug=IsEventLogging();
973 if (image_info->number_scenes != 0)
976 Generate blank images for subimage specification (e.g. image.tif[4].
978 for (i=0; i < (ssize_t) image_info->scene; i++)
980 (void) TIFFReadDirectory(tiff);
981 AcquireNextImage(image_info,image,exception);
982 if (GetNextImageInList(image) == (Image *) NULL)
984 image=DestroyImageList(image);
985 return((Image *) NULL);
987 image=SyncNextImageInList(image);
992 if (0 && (image_info->verbose != MagickFalse))
993 TIFFPrintDirectory(tiff,stdout,MagickFalse);
994 #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
995 (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
996 "lsb" : "msb",exception);
998 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
999 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
1000 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
1001 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGELENGTH,&height);
1002 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
1003 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace);
1004 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample);
1005 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format);
1006 if (sample_format == SAMPLEFORMAT_IEEEFP)
1007 (void) SetImageProperty(image,"quantum:format","floating-point",
1009 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value);
1010 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value);
1011 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric);
1012 switch (photometric)
1014 case PHOTOMETRIC_MINISBLACK:
1016 (void) SetImageProperty(image,"tiff:photometric","min-is-black",
1020 case PHOTOMETRIC_MINISWHITE:
1022 (void) SetImageProperty(image,"tiff:photometric","min-is-white",
1026 case PHOTOMETRIC_PALETTE:
1028 (void) SetImageProperty(image,"tiff:photometric","palette",exception);
1031 case PHOTOMETRIC_RGB:
1033 (void) SetImageProperty(image,"tiff:photometric","RGB",exception);
1036 case PHOTOMETRIC_CIELAB:
1038 (void) SetImageProperty(image,"tiff:photometric","CIELAB",exception);
1041 case PHOTOMETRIC_SEPARATED:
1043 (void) SetImageProperty(image,"tiff:photometric","separated",exception);
1046 case PHOTOMETRIC_YCBCR:
1048 (void) SetImageProperty(image,"tiff:photometric","YCBCR",exception);
1053 (void) SetImageProperty(image,"tiff:photometric","unknown",exception);
1057 if (image->debug != MagickFalse)
1059 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
1060 (unsigned int) width,(unsigned int) height);
1061 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
1063 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1064 "Bits per sample: %u",bits_per_sample);
1065 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1066 "Min sample value: %u",min_sample_value);
1067 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1068 "Max sample value: %u",max_sample_value);
1069 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
1070 "interpretation: %s",GetImageProperty(image,"tiff:photometric",
1073 image->columns=(size_t) width;
1074 image->rows=(size_t) height;
1075 image->depth=(size_t) bits_per_sample;
1076 if (image->debug != MagickFalse)
1077 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
1078 (double) image->depth);
1079 image->endian=MSBEndian;
1080 if (endian == FILLORDER_LSB2MSB)
1081 image->endian=LSBEndian;
1082 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1083 (photometric == PHOTOMETRIC_MINISWHITE))
1084 SetImageColorspace(image,GRAYColorspace,exception);
1085 if (photometric == PHOTOMETRIC_SEPARATED)
1086 SetImageColorspace(image,CMYKColorspace,exception);
1087 if (photometric == PHOTOMETRIC_CIELAB)
1088 SetImageColorspace(image,LabColorspace,exception);
1089 TIFFGetProfiles(tiff,image,exception);
1090 TIFFGetProperties(tiff,image,exception);
1091 option=GetImageOption(image_info,"tiff:exif-properties");
1092 if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
1093 TIFFGetEXIFProperties(tiff,image,exception);
1094 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
1095 &samples_per_pixel);
1096 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
1097 x_resolution=(float) image->resolution.x;
1098 y_resolution=(float) image->resolution.y;
1099 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution);
1100 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
1101 image->resolution.x=x_resolution;
1102 image->resolution.y=y_resolution;
1103 x_position=(float) PerceptibleReciprocal(x_resolution)*image->page.x;
1104 y_position=(float) PerceptibleReciprocal(y_resolution)*image->page.y;
1105 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
1106 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
1107 image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
1108 image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
1109 image->orientation=(OrientationType) orientation;
1110 chromaticity=(float *) NULL;
1111 (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
1112 if (chromaticity != (float *) NULL)
1114 image->chromaticity.white_point.x=chromaticity[0];
1115 image->chromaticity.white_point.y=chromaticity[1];
1117 chromaticity=(float *) NULL;
1118 (void) TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity);
1119 if (chromaticity != (float *) NULL)
1121 image->chromaticity.red_primary.x=chromaticity[0];
1122 image->chromaticity.red_primary.y=chromaticity[1];
1123 image->chromaticity.green_primary.x=chromaticity[2];
1124 image->chromaticity.green_primary.y=chromaticity[3];
1125 image->chromaticity.blue_primary.x=chromaticity[4];
1126 image->chromaticity.blue_primary.y=chromaticity[5];
1128 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
1129 if ((compress_tag != COMPRESSION_NONE) &&
1130 (TIFFIsCODECConfigured(compress_tag) == 0))
1133 ThrowReaderException(CoderError,"CompressNotSupported");
1136 switch (compress_tag)
1138 case COMPRESSION_NONE: image->compression=NoCompression; break;
1139 case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1140 case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1141 case COMPRESSION_JPEG:
1143 image->compression=JPEGCompression;
1144 #if defined(JPEG_SUPPORT)
1147 sampling_factor[MaxTextExtent];
1153 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
1154 &horizontal,&vertical);
1155 (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
1156 horizontal,vertical);
1157 (void) SetImageProperty(image,"jpeg:sampling-factor",
1158 sampling_factor,exception);
1159 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1160 "Sampling Factors: %s",sampling_factor);
1165 case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1166 #if defined(COMPRESSION_LZMA)
1167 case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1169 case COMPRESSION_LZW: image->compression=LZWCompression; break;
1170 case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1171 case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1172 default: image->compression=RLECompression; break;
1175 Allocate memory for the image and pixel buffer.
1177 quantum_info=AcquireQuantumInfo(image_info,image);
1178 if (quantum_info == (QuantumInfo *) NULL)
1181 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1183 if (sample_format == SAMPLEFORMAT_UINT)
1184 status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1185 if (sample_format == SAMPLEFORMAT_INT)
1186 status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1187 if (sample_format == SAMPLEFORMAT_IEEEFP)
1188 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1189 if (status == MagickFalse)
1191 quantum_info=DestroyQuantumInfo(quantum_info);
1193 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1196 switch (photometric)
1198 case PHOTOMETRIC_MINISBLACK:
1200 quantum_info->min_is_white=MagickFalse;
1203 case PHOTOMETRIC_MINISWHITE:
1205 quantum_info->min_is_white=MagickTrue;
1211 associated_alpha=MagickFalse;
1213 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1215 if (extra_samples == 0)
1217 if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1218 image->alpha_trait=BlendPixelTrait;
1221 for (i=0; i < extra_samples; i++)
1223 image->alpha_trait=BlendPixelTrait;
1224 if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1225 SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1227 option=GetImageOption(image_info,"tiff:alpha");
1228 if (option != (const char *) NULL)
1229 associated_alpha=LocaleCompare(option,"associated") == 0 ? MagickTrue :
1231 if (image->alpha_trait == BlendPixelTrait)
1232 (void) SetImageProperty(image,"tiff:alpha",
1233 associated_alpha != MagickFalse ? "associated" : "unassociated",
1235 if ((photometric == PHOTOMETRIC_PALETTE) &&
1236 (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1241 colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1242 if (AcquireImageColormap(image,colors,exception) == MagickFalse)
1245 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1248 if (units == RESUNIT_INCH)
1249 image->units=PixelsPerInchResolution;
1250 if (units == RESUNIT_CENTIMETER)
1251 image->units=PixelsPerCentimeterResolution;
1252 value=(unsigned short) image->scene;
1253 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages);
1255 if (image_info->ping != MagickFalse)
1257 if (image_info->number_scenes != 0)
1258 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1260 goto next_tiff_frame;
1262 method=ReadGenericMethod;
1263 if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) != 0)
1266 value[MaxTextExtent];
1268 method=ReadStripMethod;
1269 (void) FormatLocaleString(value,MaxTextExtent,"%u",
1270 (unsigned int) rows_per_strip);
1271 (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
1273 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
1274 method=ReadRGBAMethod;
1275 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
1276 method=ReadCMYKAMethod;
1277 if ((photometric != PHOTOMETRIC_RGB) &&
1278 (photometric != PHOTOMETRIC_CIELAB) &&
1279 (photometric != PHOTOMETRIC_SEPARATED))
1280 method=ReadGenericMethod;
1281 if (image->storage_class == PseudoClass)
1282 method=ReadSingleSampleMethod;
1283 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1284 (photometric == PHOTOMETRIC_MINISWHITE))
1285 method=ReadSingleSampleMethod;
1286 if ((photometric != PHOTOMETRIC_SEPARATED) &&
1287 (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1288 method=ReadGenericMethod;
1289 if (image->compression == JPEGCompression)
1290 method=ReadGenericMethod;
1291 if (TIFFIsTiled(tiff) != MagickFalse)
1292 method=ReadTileMethod;
1293 quantum_info->endian=LSBEndian;
1294 quantum_type=RGBQuantum;
1295 pixels=GetQuantumPixels(quantum_info);
1298 case ReadSingleSampleMethod:
1301 Convert TIFF image to PseudoClass MIFF image.
1303 if ((image->storage_class == PseudoClass) &&
1304 (photometric == PHOTOMETRIC_PALETTE))
1315 Initialize colormap.
1317 red_colormap=(uint16 *) NULL;
1318 green_colormap=(uint16 *) NULL;
1319 blue_colormap=(uint16 *) NULL;
1320 (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1321 &green_colormap,&blue_colormap);
1322 if ((red_colormap != (uint16 *) NULL) &&
1323 (green_colormap != (uint16 *) NULL) &&
1324 (blue_colormap != (uint16 *) NULL))
1326 range=255; /* might be old style 8-bit colormap */
1327 for (i=0; i < (ssize_t) image->colors; i++)
1328 if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1329 (blue_colormap[i] >= 256))
1334 for (i=0; i < (ssize_t) image->colors; i++)
1336 image->colormap[i].red=ClampToQuantum(((double)
1337 QuantumRange*red_colormap[i])/range);
1338 image->colormap[i].green=ClampToQuantum(((double)
1339 QuantumRange*green_colormap[i])/range);
1340 image->colormap[i].blue=ClampToQuantum(((double)
1341 QuantumRange*blue_colormap[i])/range);
1345 quantum_type=IndexQuantum;
1346 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1347 if (image->alpha_trait == BlendPixelTrait)
1349 if (image->storage_class != PseudoClass)
1351 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1353 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1357 quantum_type=IndexAlphaQuantum;
1358 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1362 if (image->storage_class != PseudoClass)
1364 quantum_type=GrayQuantum;
1365 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1367 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1368 if (status == MagickFalse)
1371 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1373 pixels=GetQuantumPixels(quantum_info);
1374 for (y=0; y < (ssize_t) image->rows; y++)
1382 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1385 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1386 if (q == (Quantum *) NULL)
1388 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1389 quantum_type,pixels,exception);
1391 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1393 if (image->previous == (Image *) NULL)
1395 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1397 if (status == MagickFalse)
1403 case ReadRGBAMethod:
1406 Convert TIFF image to DirectClass MIFF image.
1408 pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1409 quantum_type=RGBQuantum;
1410 if (image->alpha_trait == BlendPixelTrait)
1412 quantum_type=RGBAQuantum;
1413 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1415 if (image->colorspace == CMYKColorspace)
1417 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1418 quantum_type=CMYKQuantum;
1419 if (image->alpha_trait == BlendPixelTrait)
1421 quantum_type=CMYKAQuantum;
1422 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1425 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1426 if (status == MagickFalse)
1429 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1431 pixels=GetQuantumPixels(quantum_info);
1432 for (y=0; y < (ssize_t) image->rows; y++)
1440 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1443 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1444 if (q == (Quantum *) NULL)
1446 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1447 quantum_type,pixels,exception);
1448 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1450 if (image->previous == (Image *) NULL)
1452 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1454 if (status == MagickFalse)
1460 case ReadCMYKAMethod:
1463 Convert TIFF image to DirectClass MIFF image.
1465 for (i=0; i < (ssize_t) samples_per_pixel; i++)
1467 for (y=0; y < (ssize_t) image->rows; y++)
1475 status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1479 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1480 if (q == (Quantum *) NULL)
1482 if (image->colorspace != CMYKColorspace)
1485 case 0: quantum_type=RedQuantum; break;
1486 case 1: quantum_type=GreenQuantum; break;
1487 case 2: quantum_type=BlueQuantum; break;
1488 case 3: quantum_type=AlphaQuantum; break;
1489 default: quantum_type=UndefinedQuantum; break;
1494 case 0: quantum_type=CyanQuantum; break;
1495 case 1: quantum_type=MagentaQuantum; break;
1496 case 2: quantum_type=YellowQuantum; break;
1497 case 3: quantum_type=BlackQuantum; break;
1498 case 4: quantum_type=AlphaQuantum; break;
1499 default: quantum_type=UndefinedQuantum; break;
1501 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1502 quantum_type,pixels,exception);
1503 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1506 if (image->previous == (Image *) NULL)
1508 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1510 if (status == MagickFalse)
1516 case ReadStripMethod:
1522 Convert stripped TIFF image to DirectClass MIFF image.
1526 for (y=0; y < (ssize_t) image->rows; y++)
1534 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1535 if (q == (Quantum *) NULL)
1539 if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1541 i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1545 p=((uint32 *) pixels)+image->columns*i;
1546 for (x=0; x < (ssize_t) image->columns; x++)
1548 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1550 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1552 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1554 if (image->alpha_trait == BlendPixelTrait)
1555 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1558 q+=GetPixelChannels(image);
1560 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1562 if (image->previous == (Image *) NULL)
1564 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1566 if (status == MagickFalse)
1572 case ReadTileMethod:
1586 Convert tiled TIFF image to DirectClass MIFF image.
1588 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) == 0) ||
1589 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) == 0))
1592 ThrowReaderException(CoderError,"ImageIsNotTiled");
1594 (void) SetImageStorageClass(image,DirectClass,exception);
1595 number_pixels=columns*rows;
1596 tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
1597 sizeof(*tile_pixels));
1598 if (tile_pixels == (uint32 *) NULL)
1601 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1603 for (y=0; y < (ssize_t) image->rows; y+=rows)
1616 rows_remaining=image->rows-y;
1617 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1618 rows_remaining=rows;
1619 tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1621 if (tile == (Quantum *) NULL)
1623 for (x=0; x < (ssize_t) image->columns; x+=columns)
1629 if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1631 columns_remaining=image->columns-x;
1632 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1633 columns_remaining=columns;
1634 p=tile_pixels+(rows-rows_remaining)*columns;
1635 q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1637 for (row=rows_remaining; row > 0; row--)
1639 if (image->alpha_trait == BlendPixelTrait)
1640 for (column=columns_remaining; column > 0; column--)
1642 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1644 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1646 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1648 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1651 q+=GetPixelChannels(image);
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)
1663 q+=GetPixelChannels(image);
1665 p+=columns-columns_remaining;
1666 q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1669 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1671 if (image->previous == (Image *) NULL)
1673 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1675 if (status == MagickFalse)
1679 tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
1682 case ReadGenericMethod:
1695 Convert TIFF image to DirectClass MIFF image.
1697 number_pixels=(MagickSizeType) image->columns*image->rows;
1698 if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
1699 (number_pixels*sizeof(uint32))))
1702 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1704 pixel_info=AcquireVirtualMemory(image->columns,image->rows*
1706 if (pixel_info == (MemoryInfo *) NULL)
1709 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1711 pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
1712 (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
1713 (uint32) image->rows,(uint32 *) pixels,0);
1715 Convert image to DirectClass pixel packets.
1717 p=pixels+number_pixels-1;
1718 for (y=0; y < (ssize_t) image->rows; y++)
1726 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1727 if (q == (Quantum *) NULL)
1729 q+=GetPixelChannels(image)*(image->columns-1);
1730 for (x=0; x < (ssize_t) image->columns; x++)
1732 SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),
1734 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1736 SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),
1738 if (image->alpha_trait == BlendPixelTrait)
1739 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1742 q-=GetPixelChannels(image);;
1744 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1746 if (image->previous == (Image *) NULL)
1748 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1750 if (status == MagickFalse)
1754 pixel_info=RelinquishVirtualMemory(pixel_info);
1758 SetQuantumImageType(image,quantum_type);
1760 quantum_info=DestroyQuantumInfo(quantum_info);
1761 if (photometric == PHOTOMETRIC_CIELAB)
1762 DecodeLabImage(image,exception);
1763 if ((photometric == PHOTOMETRIC_LOGL) ||
1764 (photometric == PHOTOMETRIC_MINISBLACK) ||
1765 (photometric == PHOTOMETRIC_MINISWHITE))
1767 image->type=GrayscaleType;
1768 if (bits_per_sample == 1)
1769 image->type=BilevelType;
1771 if (image->storage_class == PseudoClass)
1772 image->depth=GetImageDepth(image,exception);
1774 Proceed to next image.
1776 if (image_info->number_scenes != 0)
1777 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1779 status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1780 if (status == MagickTrue)
1783 Allocate next image structure.
1785 AcquireNextImage(image_info,image,exception);
1786 if (GetNextImageInList(image) == (Image *) NULL)
1788 image=DestroyImageList(image);
1789 return((Image *) NULL);
1791 image=SyncNextImageInList(image);
1792 status=SetImageProgress(image,LoadImagesTag,image->scene-1,
1794 if (status == MagickFalse)
1797 } while (status == MagickTrue);
1798 (void) TIFFSetWarningHandler(warning_handler);
1799 (void) TIFFSetErrorHandler(error_handler);
1801 return(GetFirstImageInList(image));
1806 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1810 % R e g i s t e r T I F F I m a g e %
1814 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1816 % RegisterTIFFImage() adds properties for the TIFF image format to
1817 % the list of supported formats. The properties include the image format
1818 % tag, a method to read and/or write the format, whether the format
1819 % supports the saving of more than one frame to the same file or blob,
1820 % whether the format supports native in-memory I/O, and a brief
1821 % description of the format.
1823 % The format of the RegisterTIFFImage method is:
1825 % size_t RegisterTIFFImage(void)
1829 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1830 static TIFFExtendProc
1831 tag_extender = (TIFFExtendProc) NULL;
1833 static void TIFFTagExtender(TIFF *tiff)
1835 static const TIFFFieldInfo
1838 { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1839 (char *) "PhotoshopLayerData" },
1840 { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
1841 (char *) "Microscope" }
1844 TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
1845 sizeof(*TIFFExtensions));
1846 if (tag_extender != (TIFFExtendProc) NULL)
1847 (*tag_extender)(tiff);
1851 ModuleExport size_t RegisterTIFFImage(void)
1853 #define TIFFDescription "Tagged Image File Format"
1856 version[MaxTextExtent];
1861 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1862 tiff_semaphore=AllocateSemaphoreInfo();
1863 LockSemaphoreInfo(tiff_semaphore);
1864 if (instantiate_key == MagickFalse)
1866 if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
1867 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1868 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
1869 if (tag_extender == (TIFFExtendProc) NULL)
1870 tag_extender=TIFFSetTagExtender(TIFFTagExtender);
1872 instantiate_key=MagickTrue;
1874 UnlockSemaphoreInfo(tiff_semaphore);
1876 #if defined(TIFF_VERSION)
1877 (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
1879 #if defined(MAGICKCORE_TIFF_DELEGATE)
1888 for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
1894 entry=SetMagickInfo("GROUP4");
1895 #if defined(MAGICKCORE_TIFF_DELEGATE)
1896 entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
1897 entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
1899 entry->raw=MagickTrue;
1900 entry->endian_support=MagickTrue;
1901 entry->adjoin=MagickFalse;
1902 entry->format_type=ImplicitFormatType;
1903 entry->seekable_stream=MagickTrue;
1904 entry->thread_support=NoThreadSupport;
1905 entry->description=ConstantString("Raw CCITT Group4");
1906 entry->mime_type=ConstantString("image/tiff");
1907 entry->module=ConstantString("TIFF");
1908 (void) RegisterMagickInfo(entry);
1909 entry=SetMagickInfo("PTIF");
1910 #if defined(MAGICKCORE_TIFF_DELEGATE)
1911 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1912 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1914 entry->endian_support=MagickTrue;
1915 entry->seekable_stream=MagickTrue;
1916 entry->thread_support=NoThreadSupport;
1917 entry->description=ConstantString("Pyramid encoded TIFF");
1918 entry->mime_type=ConstantString("image/tiff");
1919 entry->module=ConstantString("TIFF");
1920 (void) RegisterMagickInfo(entry);
1921 entry=SetMagickInfo("TIF");
1922 #if defined(MAGICKCORE_TIFF_DELEGATE)
1923 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1924 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1926 entry->endian_support=MagickTrue;
1927 entry->seekable_stream=MagickTrue;
1928 entry->stealth=MagickTrue;
1929 entry->thread_support=NoThreadSupport;
1930 entry->description=ConstantString(TIFFDescription);
1931 if (*version != '\0')
1932 entry->version=ConstantString(version);
1933 entry->mime_type=ConstantString("image/tiff");
1934 entry->module=ConstantString("TIFF");
1935 (void) RegisterMagickInfo(entry);
1936 entry=SetMagickInfo("TIFF");
1937 #if defined(MAGICKCORE_TIFF_DELEGATE)
1938 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1939 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1941 entry->magick=(IsImageFormatHandler *) IsTIFF;
1942 entry->endian_support=MagickTrue;
1943 entry->seekable_stream=MagickTrue;
1944 entry->thread_support=NoThreadSupport;
1945 entry->description=ConstantString(TIFFDescription);
1946 if (*version != '\0')
1947 entry->version=ConstantString(version);
1948 entry->mime_type=ConstantString("image/tiff");
1949 entry->module=ConstantString("TIFF");
1950 (void) RegisterMagickInfo(entry);
1951 entry=SetMagickInfo("TIFF64");
1952 #if defined(TIFF_VERSION_BIG)
1953 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1954 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1956 entry->adjoin=MagickFalse;
1957 entry->endian_support=MagickTrue;
1958 entry->seekable_stream=MagickTrue;
1959 entry->thread_support=NoThreadSupport;
1960 entry->description=ConstantString("Tagged Image File Format (64-bit)");
1961 if (*version != '\0')
1962 entry->version=ConstantString(version);
1963 entry->mime_type=ConstantString("image/tiff");
1964 entry->module=ConstantString("TIFF");
1965 (void) RegisterMagickInfo(entry);
1966 return(MagickImageCoderSignature);
1970 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1974 % U n r e g i s t e r T I F F I m a g e %
1978 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1980 % UnregisterTIFFImage() removes format registrations made by the TIFF module
1981 % from the list of supported formats.
1983 % The format of the UnregisterTIFFImage method is:
1985 % UnregisterTIFFImage(void)
1988 ModuleExport void UnregisterTIFFImage(void)
1990 (void) UnregisterMagickInfo("TIFF64");
1991 (void) UnregisterMagickInfo("TIFF");
1992 (void) UnregisterMagickInfo("TIF");
1993 (void) UnregisterMagickInfo("PTIF");
1994 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1995 tiff_semaphore=AllocateSemaphoreInfo();
1996 LockSemaphoreInfo(tiff_semaphore);
1997 if (instantiate_key != MagickFalse)
1999 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
2000 if (tag_extender == (TIFFExtendProc) NULL)
2001 (void) TIFFSetTagExtender(tag_extender);
2003 if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
2004 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
2005 instantiate_key=MagickFalse;
2007 UnlockSemaphoreInfo(tiff_semaphore);
2008 DestroySemaphoreInfo(&tiff_semaphore);
2011 #if defined(MAGICKCORE_TIFF_DELEGATE)
2013 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2017 % W r i t e G R O U P 4 I m a g e %
2021 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2023 % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
2025 % The format of the WriteGROUP4Image method is:
2027 % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2028 % Image *image,ExceptionInfo *)
2030 % A description of each parameter follows:
2032 % o image_info: the image info.
2034 % o image: The image.
2036 % o exception: return any errors or warnings in this structure.
2039 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
2040 Image *image,ExceptionInfo *exception)
2043 filename[MaxTextExtent];
2077 Write image as CCITT Group4 TIFF image to a temporary file.
2079 assert(image_info != (const ImageInfo *) NULL);
2080 assert(image_info->signature == MagickSignature);
2081 assert(image != (Image *) NULL);
2082 assert(image->signature == MagickSignature);
2083 if (image->debug != MagickFalse)
2084 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2085 assert(exception != (ExceptionInfo *) NULL);
2086 assert(exception->signature == MagickSignature);
2087 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2088 if (status == MagickFalse)
2090 huffman_image=CloneImage(image,0,0,MagickTrue,exception);
2091 if (huffman_image == (Image *) NULL)
2093 (void) CloseBlob(image);
2094 return(MagickFalse);
2096 huffman_image->endian=MSBEndian;
2098 unique_file=AcquireUniqueFileResource(filename);
2099 if (unique_file != -1)
2100 file=fdopen(unique_file,"wb");
2101 if ((unique_file == -1) || (file == (FILE *) NULL))
2103 ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
2105 return(MagickFalse);
2107 (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
2109 (void) SetImageType(huffman_image,BilevelType,exception);
2110 write_info=CloneImageInfo((ImageInfo *) NULL);
2111 SetImageInfoFile(write_info,file);
2112 write_info->compression=Group4Compression;
2113 write_info->type=BilevelType;
2114 (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
2115 status=WriteTIFFImage(write_info,huffman_image,exception);
2116 (void) fflush(file);
2117 write_info=DestroyImageInfo(write_info);
2118 if (status == MagickFalse)
2120 huffman_image=DestroyImage(huffman_image);
2121 (void) fclose(file);
2122 (void) RelinquishUniqueFileResource(filename);
2123 return(MagickFalse);
2125 tiff=TIFFOpen(filename,"rb");
2126 if (tiff == (TIFF *) NULL)
2128 huffman_image=DestroyImage(huffman_image);
2129 (void) fclose(file);
2130 (void) RelinquishUniqueFileResource(filename);
2131 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
2132 image_info->filename);
2133 return(MagickFalse);
2136 Allocate raw strip buffer.
2138 if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2141 huffman_image=DestroyImage(huffman_image);
2142 (void) fclose(file);
2143 (void) RelinquishUniqueFileResource(filename);
2144 return(MagickFalse);
2146 strip_size=byte_count[0];
2147 for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2148 if (byte_count[i] > strip_size)
2149 strip_size=byte_count[i];
2150 buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2152 if (buffer == (unsigned char *) NULL)
2155 huffman_image=DestroyImage(huffman_image);
2156 (void) fclose(file);
2157 (void) RelinquishUniqueFileResource(filename);
2158 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2159 image_info->filename);
2162 Compress runlength encoded to 2D Huffman pixels.
2164 for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2166 count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2167 if (WriteBlob(image,(size_t) count,buffer) != count)
2170 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2172 huffman_image=DestroyImage(huffman_image);
2173 (void) fclose(file);
2174 (void) RelinquishUniqueFileResource(filename);
2175 (void) CloseBlob(image);
2180 #if defined(MAGICKCORE_TIFF_DELEGATE)
2182 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2186 % W r i t e P T I F I m a g e %
2190 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2192 % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2195 % The format of the WritePTIFImage method is:
2197 % MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2198 % Image *image,ExceptionInfo *exception)
2200 % A description of each parameter follows:
2202 % o image_info: the image info.
2204 % o image: The image.
2206 % o exception: return any errors or warnings in this structure.
2209 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2210 Image *image,ExceptionInfo *exception)
2231 Create pyramid-encoded TIFF image.
2233 images=NewImageList();
2234 for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2236 AppendImageToList(&images,CloneImage(next,0,0,MagickFalse,exception));
2237 columns=next->columns;
2239 resolution=next->resolution;
2240 while ((columns > 64) && (rows > 64))
2246 pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
2247 if (pyramid_image == (Image *) NULL)
2249 pyramid_image->resolution=resolution;
2250 AppendImageToList(&images,pyramid_image);
2253 images=GetFirstImageInList(images);
2255 Write pyramid-encoded TIFF image.
2257 write_info=CloneImageInfo(image_info);
2258 write_info->adjoin=MagickTrue;
2259 (void) CopyMagickString(write_info->magick,"TIFF",MaxTextExtent);
2260 (void) CopyMagickString(images->magick,"TIFF",MaxTextExtent);
2261 status=WriteTIFFImage(write_info,images,exception);
2262 images=DestroyImageList(images);
2263 write_info=DestroyImageInfo(write_info);
2268 #if defined(MAGICKCORE_TIFF_DELEGATE)
2270 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2273 % W r i t e T I F F I m a g e %
2277 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % WriteTIFFImage() writes an image in the Tagged image file format.
2281 % The format of the WriteTIFFImage method is:
2283 % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2284 % Image *image,ExceptionInfo *exception)
2286 % A description of each parameter follows:
2288 % o image_info: the image info.
2290 % o image: The image.
2292 % o exception: return any errors or warnings in this structure.
2296 typedef struct _TIFFInfo
2307 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2309 assert(tiff_info != (TIFFInfo *) NULL);
2310 if (tiff_info->scanlines != (unsigned char *) NULL)
2311 tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2312 tiff_info->scanlines);
2313 if (tiff_info->pixels != (unsigned char *) NULL)
2314 tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2318 static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
2330 image_view=AcquireAuthenticCacheView(image,exception);
2331 for (y=0; y < (ssize_t) image->rows; y++)
2339 if (status == MagickFalse)
2341 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2342 if (q == (Quantum *) NULL)
2347 for (x=0; x < (ssize_t) image->columns; x++)
2353 a=QuantumScale*GetPixela(image,q)-0.5;
2356 b=QuantumScale*GetPixelb(image,q)-0.5;
2359 SetPixela(image,QuantumRange*a,q);
2360 SetPixelb(image,QuantumRange*b,q);
2361 q+=GetPixelChannels(image);
2363 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2366 image_view=DestroyCacheView(image_view);
2370 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
2371 TIFF *tiff,TIFFInfo *tiff_info)
2383 assert(tiff_info != (TIFFInfo *) NULL);
2384 (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2385 option=GetImageOption(image_info,"tiff:tile-geometry");
2386 if (option == (const char *) NULL)
2388 flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2389 if ((flags & HeightValue) == 0)
2390 tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2391 tile_columns=(uint32) tiff_info->tile_geometry.width;
2392 tile_rows=(uint32) tiff_info->tile_geometry.height;
2393 TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2394 (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2395 (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2396 tiff_info->tile_geometry.width=tile_columns;
2397 tiff_info->tile_geometry.height=tile_rows;
2398 tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2399 tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2400 tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2401 tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2402 if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2403 (tiff_info->pixels == (unsigned char *) NULL))
2405 DestroyTIFFInfo(tiff_info);
2406 return(MagickFalse);
2411 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2412 tsample_t sample,Image *image)
2420 register unsigned char
2434 if (TIFFIsTiled(tiff) == 0)
2435 return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2437 Fill scanlines to tile height.
2439 i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2440 (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2441 (size_t) TIFFScanlineSize(tiff));
2442 if (((size_t) (row % tiff_info->tile_geometry.height) !=
2443 (tiff_info->tile_geometry.height-1)) &&
2444 (row != (ssize_t) (image->rows-1)))
2447 Write tile to TIFF image.
2450 bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (
2451 tiff_info->tile_geometry.height*tiff_info->tile_geometry.width);
2452 number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2453 tiff_info->tile_geometry.width;
2454 for (i=0; i < (ssize_t) number_tiles; i++)
2456 tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2457 tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2458 for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2459 for (k=0; k < (ssize_t) tile_width; k++)
2461 if (bytes_per_pixel == 0)
2463 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2464 tiff_info->tile_geometry.width+k)/8);
2465 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2469 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2470 tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2471 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2472 for (l=0; l < bytes_per_pixel; l++)
2475 if ((i*tiff_info->tile_geometry.width) != image->columns)
2476 status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2477 tiff_info->tile_geometry.width),(uint32) ((row/
2478 tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2486 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2494 if (image->profiles == (void *) NULL)
2496 ResetImageProfileIterator(image);
2497 for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2499 profile=GetImageProfile(image,name);
2500 if (GetStringInfoLength(profile) == 0)
2502 name=GetNextImageProfile(image);
2505 #if defined(TIFFTAG_XMLPACKET)
2506 if (LocaleCompare(name,"xmp") == 0)
2507 (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2508 profile),GetStringInfoDatum(profile));
2510 #if defined(TIFFTAG_ICCPROFILE)
2511 if (LocaleCompare(name,"icc") == 0)
2512 (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2513 profile),GetStringInfoDatum(profile));
2515 if (LocaleCompare(name,"iptc") == 0)
2523 iptc_profile=CloneStringInfo(profile);
2524 length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2526 SetStringInfoLength(iptc_profile,length);
2527 if (TIFFIsByteSwapped(tiff))
2528 TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2529 (unsigned long) (length/4));
2530 (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2531 GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2532 iptc_profile=DestroyStringInfo(iptc_profile);
2534 #if defined(TIFFTAG_PHOTOSHOP)
2535 if (LocaleCompare(name,"8bim") == 0)
2536 (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2537 GetStringInfoLength(profile),GetStringInfoDatum(profile));
2539 if (LocaleCompare(name,"tiff:37724") == 0)
2540 (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
2541 GetStringInfoDatum(profile));
2542 if (LocaleCompare(name,"tiff:34118") == 0)
2543 (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
2544 GetStringInfoDatum(profile));
2545 name=GetNextImageProfile(image);
2549 static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
2554 (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
2555 value=GetImageProperty(image,"tiff:hostcomputer",exception);
2556 if (value != (const char *) NULL)
2557 (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2558 value=GetImageProperty(image,"tiff:artist",exception);
2559 if (value != (const char *) NULL)
2560 (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2561 value=GetImageProperty(image,"tiff:timestamp",exception);
2562 if (value != (const char *) NULL)
2563 (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2564 value=GetImageProperty(image,"tiff:make",exception);
2565 if (value != (const char *) NULL)
2566 (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2567 value=GetImageProperty(image,"tiff:model",exception);
2568 if (value != (const char *) NULL)
2569 (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2570 value=GetImageProperty(image,"tiff:software",exception);
2571 if (value != (const char *) NULL)
2572 (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2573 value=GetImageProperty(image,"tiff:copyright",exception);
2574 if (value != (const char *) NULL)
2575 (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
2576 value=GetImageProperty(image,"kodak-33423",exception);
2577 if (value != (const char *) NULL)
2578 (void) TIFFSetField(tiff,33423,value);
2579 value=GetImageProperty(image,"kodak-36867",exception);
2580 if (value != (const char *) NULL)
2581 (void) TIFFSetField(tiff,36867,value);
2582 value=GetImageProperty(image,"label",exception);
2583 if (value != (const char *) NULL)
2584 (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
2585 value=GetImageProperty(image,"comment",exception);
2586 if (value != (const char *) NULL)
2587 (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
2590 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
2591 ExceptionInfo *exception)
2593 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
2604 Write EXIF properties.
2607 (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
2608 for (i=0; exif_info[i].tag != 0; i++)
2610 value=GetImageProperty(image,exif_info[i].property,exception);
2611 if (value == (const char *) NULL)
2613 switch (exif_info[i].type)
2617 (void) TIFFSetField(tiff,exif_info[i].tag,value);
2625 shorty=(uint16) StringToLong(value);
2626 (void) TIFFSetField(tiff,exif_info[i].tag,shorty);
2634 ssize_ty=(uint16) StringToLong(value);
2635 (void) TIFFSetField(tiff,exif_info[i].tag,ssize_ty);
2639 case TIFF_SRATIONAL:
2644 rational=StringToDouble(value,(char **) NULL);
2645 (void) TIFFSetField(tiff,exif_info[i].tag,rational);
2652 /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
2659 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2660 Image *image,ExceptionInfo *exception)
2662 #if !defined(TIFFDefaultStripSize)
2663 #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
2723 assert(image_info != (const ImageInfo *) NULL);
2724 assert(image_info->signature == MagickSignature);
2725 assert(image != (Image *) NULL);
2726 assert(image->signature == MagickSignature);
2727 if (image->debug != MagickFalse)
2728 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2729 assert(exception != (ExceptionInfo *) NULL);
2730 assert(exception->signature == MagickSignature);
2731 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2732 if (status == MagickFalse)
2734 (void) MagickSetThreadValue(tiff_exception,exception);
2735 error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
2736 warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
2737 endian_type=UndefinedEndian;
2738 option=GetImageOption(image_info,"tiff:endian");
2739 if (option != (const char *) NULL)
2741 if (LocaleNCompare(option,"msb",3) == 0)
2742 endian_type=MSBEndian;
2743 if (LocaleNCompare(option,"lsb",3) == 0)
2744 endian_type=LSBEndian;;
2746 switch (endian_type)
2748 case LSBEndian: mode="wl"; break;
2749 case MSBEndian: mode="wb"; break;
2750 default: mode="w"; break;
2752 #if defined(TIFF_VERSION_BIG)
2753 if (LocaleCompare(image_info->magick,"TIFF64") == 0)
2754 switch (endian_type)
2756 case LSBEndian: mode="wl8"; break;
2757 case MSBEndian: mode="wb8"; break;
2758 default: mode="w8"; break;
2761 tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
2762 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
2764 if (tiff == (TIFF *) NULL)
2766 (void) TIFFSetWarningHandler(warning_handler);
2767 (void) TIFFSetErrorHandler(error_handler);
2768 return(MagickFalse);
2771 debug=IsEventLogging();
2776 Initialize TIFF fields.
2778 if ((image_info->type != UndefinedType) &&
2779 (image_info->type != OptimizeType))
2780 (void) SetImageType(image,image_info->type,exception);
2781 quantum_info=AcquireQuantumInfo(image_info,image);
2782 if (quantum_info == (QuantumInfo *) NULL)
2783 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2784 if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
2785 (quantum_info->format == UndefinedQuantumFormat) &&
2786 (IsHighDynamicRangeImage(image,exception) != MagickFalse))
2788 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
2789 if (status == MagickFalse)
2790 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2792 if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
2793 (GetPreviousImageInList(image) != (Image *) NULL))
2794 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
2795 if ((image->columns != (uint32) image->columns) ||
2796 (image->rows != (uint32) image->rows))
2797 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
2798 (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
2799 (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
2800 compression=image->compression;
2801 if (image_info->compression != UndefinedCompression)
2802 compression=image_info->compression;
2803 switch (compression)
2805 case FaxCompression:
2807 compress_tag=COMPRESSION_CCITTFAX3;
2808 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2811 case Group4Compression:
2813 compress_tag=COMPRESSION_CCITTFAX4;
2814 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2817 #if defined(COMPRESSION_JBIG)
2818 case JBIG1Compression:
2820 compress_tag=COMPRESSION_JBIG;
2824 case JPEGCompression:
2826 compress_tag=COMPRESSION_JPEG;
2829 #if defined(COMPRESSION_LZMA)
2830 case LZMACompression:
2832 compress_tag=COMPRESSION_LZMA;
2836 case LZWCompression:
2838 compress_tag=COMPRESSION_LZW;
2841 case RLECompression:
2843 compress_tag=COMPRESSION_PACKBITS;
2846 case ZipCompression:
2848 compress_tag=COMPRESSION_ADOBE_DEFLATE;
2854 compress_tag=COMPRESSION_NONE;
2858 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
2859 if ((compress_tag != COMPRESSION_NONE) &&
2860 (TIFFIsCODECConfigured(compress_tag) == 0))
2862 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2863 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2864 MagickCompressOptions,(ssize_t) compression));
2865 compress_tag=COMPRESSION_NONE;
2866 compression=NoCompression;
2869 switch (compress_tag)
2871 #if defined(CCITT_SUPPORT)
2872 case COMPRESSION_CCITTFAX3:
2873 case COMPRESSION_CCITTFAX4:
2875 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
2876 case COMPRESSION_JPEG:
2878 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2879 case COMPRESSION_LZMA:
2881 #if defined(LZW_SUPPORT)
2882 case COMPRESSION_LZW:
2884 #if defined(PACKBITS_SUPPORT)
2885 case COMPRESSION_PACKBITS:
2887 #if defined(ZIP_SUPPORT)
2888 case COMPRESSION_ADOBE_DEFLATE:
2890 case COMPRESSION_NONE:
2894 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2895 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2896 MagickCompressOptions,(ssize_t) compression));
2897 compress_tag=COMPRESSION_NONE;
2898 compression=NoCompression;
2903 switch (compression)
2905 case FaxCompression:
2906 case Group4Compression:
2908 (void) SetImageType(image,BilevelType,exception);
2911 case JPEGCompression:
2913 (void) SetImageStorageClass(image,DirectClass,exception);
2914 (void) SetImageDepth(image,8,exception);
2920 if (image->colorspace == CMYKColorspace)
2922 photometric=PHOTOMETRIC_SEPARATED;
2923 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
2924 (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
2929 Full color TIFF raster.
2931 if (image->colorspace == LabColorspace)
2933 photometric=PHOTOMETRIC_CIELAB;
2934 EncodeLabImage(image,exception);
2937 if (image->colorspace == YCbCrColorspace)
2939 photometric=PHOTOMETRIC_YCBCR;
2940 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
2941 (void) SetImageStorageClass(image,DirectClass,exception);
2942 (void) SetImageDepth(image,8,exception);
2945 photometric=PHOTOMETRIC_RGB;
2946 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
2947 if ((image_info->type != TrueColorType) &&
2948 (image_info->type != TrueColorMatteType))
2950 if ((image_info->type != PaletteType) &&
2951 (IsImageGray(image,exception) != MagickFalse))
2953 photometric=(uint16) (quantum_info->min_is_white !=
2954 MagickFalse ? PHOTOMETRIC_MINISWHITE :
2955 PHOTOMETRIC_MINISBLACK);
2956 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2957 if ((image_info->depth == 0) &&
2958 (image->alpha_trait != BlendPixelTrait) &&
2959 (IsImageMonochrome(image,exception) != MagickFalse))
2961 status=SetQuantumDepth(image,quantum_info,1);
2962 if (status == MagickFalse)
2963 ThrowWriterException(ResourceLimitError,
2964 "MemoryAllocationFailed");
2968 if (image->storage_class == PseudoClass)
2974 Colormapped TIFF raster.
2976 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2977 photometric=PHOTOMETRIC_PALETTE;
2979 while ((GetQuantumRange(depth)+1) < image->colors)
2981 status=SetQuantumDepth(image,quantum_info,depth);
2982 if (status == MagickFalse)
2983 ThrowWriterException(ResourceLimitError,
2984 "MemoryAllocationFailed");
2988 if ((photometric == PHOTOMETRIC_RGB) &&
2989 (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
2990 (void) TransformImageColorspace(image,sRGBColorspace,exception);
2991 switch (image->endian)
2995 endian=FILLORDER_LSB2MSB;
3000 endian=FILLORDER_MSB2LSB;
3003 case UndefinedEndian:
3006 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
3010 if ((compress_tag == COMPRESSION_CCITTFAX3) &&
3011 (photometric != PHOTOMETRIC_MINISWHITE))
3013 compress_tag=COMPRESSION_NONE;
3014 endian=FILLORDER_MSB2LSB;
3017 if ((compress_tag == COMPRESSION_CCITTFAX4) &&
3018 (photometric != PHOTOMETRIC_MINISWHITE))
3020 compress_tag=COMPRESSION_NONE;
3021 endian=FILLORDER_MSB2LSB;
3023 option=GetImageOption(image_info,"tiff:fill-order");
3024 if (option != (const char *) NULL)
3026 if (LocaleNCompare(option,"msb",3) == 0)
3027 endian=FILLORDER_MSB2LSB;
3028 if (LocaleNCompare(option,"lsb",3) == 0)
3029 endian=FILLORDER_LSB2MSB;
3031 (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
3032 (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
3033 (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
3034 if (image->alpha_trait == BlendPixelTrait)
3042 TIFF has a matte channel.
3045 sample_info[0]=EXTRASAMPLE_UNASSALPHA;
3046 option=GetImageOption(image_info,"tiff:alpha");
3047 if ((option != (const char *) NULL) &&
3048 (LocaleCompare(option,"associated") == 0))
3049 sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
3050 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
3051 &samples_per_pixel);
3052 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
3053 (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
3055 if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
3056 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
3058 (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
3059 switch (quantum_info->format)
3061 case FloatingPointQuantumFormat:
3063 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
3064 (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
3065 (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
3068 case SignedQuantumFormat:
3070 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
3073 case UnsignedQuantumFormat:
3075 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
3081 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
3082 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
3083 if (photometric == PHOTOMETRIC_RGB)
3084 if ((image_info->interlace == PlaneInterlace) ||
3085 (image_info->interlace == PartitionInterlace))
3086 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
3087 rows_per_strip=TIFFDefaultStripSize(tiff,0);
3088 option=GetImageOption(image_info,"tiff:rows-per-strip");
3089 if (option != (const char *) NULL)
3090 rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
3091 switch (compress_tag)
3093 case COMPRESSION_JPEG:
3095 #if defined(JPEG_SUPPORT)
3105 rows_per_strip+=(16-(rows_per_strip % 16));
3106 if (image->quality != 0)
3107 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image->quality);
3108 if (image_info->quality != UndefinedCompressionQuality)
3109 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
3110 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
3111 if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
3116 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
3117 sampling_factor=(const char *) NULL;
3118 value=GetImageProperty(image,"jpeg:sampling-factor",exception);
3119 if (value != (char *) NULL)
3121 sampling_factor=value;
3122 if (image->debug != MagickFalse)
3123 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
3124 " Input sampling-factors=%s",sampling_factor);
3126 if (image_info->sampling_factor != (char *) NULL)
3127 sampling_factor=image_info->sampling_factor;
3128 if (sampling_factor != (const char *) NULL)
3130 flags=ParseGeometry(sampling_factor,&geometry_info);
3131 if ((flags & SigmaValue) == 0)
3132 geometry_info.sigma=geometry_info.rho;
3133 if (image->colorspace == YCbCrColorspace)
3134 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
3135 geometry_info.rho,(uint16) geometry_info.sigma);
3138 if (bits_per_sample == 12)
3139 (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
3143 case COMPRESSION_ADOBE_DEFLATE:
3145 rows_per_strip=(uint32) image->rows;
3146 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3148 if (((photometric == PHOTOMETRIC_RGB) ||
3149 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3150 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3151 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3152 (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
3153 image_info->quality == UndefinedCompressionQuality ? 7 :
3154 MagickMin((ssize_t) image_info->quality/10,9)));
3157 case COMPRESSION_CCITTFAX3:
3162 rows_per_strip=(uint32) image->rows;
3163 (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
3166 case COMPRESSION_CCITTFAX4:
3168 rows_per_strip=(uint32) image->rows;
3171 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
3172 case COMPRESSION_LZMA:
3174 if (((photometric == PHOTOMETRIC_RGB) ||
3175 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3176 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3177 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3178 (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
3179 image_info->quality == UndefinedCompressionQuality ? 7 :
3180 MagickMin((ssize_t) image_info->quality/10,9)));
3184 case COMPRESSION_LZW:
3186 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
3188 if (((photometric == PHOTOMETRIC_RGB) ||
3189 (photometric == PHOTOMETRIC_MINISBLACK)) &&
3190 ((bits_per_sample == 8) || (bits_per_sample == 16)))
3191 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
3197 if (rows_per_strip < 1)
3199 if ((image->rows/rows_per_strip) >= (1UL << 15))
3200 rows_per_strip=(image->rows >> 15);
3201 (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
3202 if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
3208 Set image resolution.
3211 if (image->units == PixelsPerInchResolution)
3213 if (image->units == PixelsPerCentimeterResolution)
3214 units=RESUNIT_CENTIMETER;
3215 (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
3216 (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
3217 (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
3218 if ((image->page.x < 0) || (image->page.y < 0))
3219 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
3220 "TIFF: negative image positions unsupported","%s",image->filename);
3221 if ((image->page.x > 0) && (image->resolution.x > 0.0))
3224 Set horizontal image position.
3226 (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
3227 image->resolution.x);
3229 if ((image->page.y > 0) && (image->resolution.y > 0.0))
3232 Set vertical image position.
3234 (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
3235 image->resolution.y);
3238 if (image->chromaticity.white_point.x != 0.0)
3244 Set image chromaticity.
3246 chromaticity[0]=(float) image->chromaticity.red_primary.x;
3247 chromaticity[1]=(float) image->chromaticity.red_primary.y;
3248 chromaticity[2]=(float) image->chromaticity.green_primary.x;
3249 chromaticity[3]=(float) image->chromaticity.green_primary.y;
3250 chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3251 chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3252 (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3253 chromaticity[0]=(float) image->chromaticity.white_point.x;
3254 chromaticity[1]=(float) image->chromaticity.white_point.y;
3255 (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3257 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3258 (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3260 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3261 if (image->scene != 0)
3262 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3263 GetImageListLength(image));
3265 if (image->orientation != UndefinedOrientation)
3266 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3267 (void) TIFFSetProfiles(tiff,image);
3273 page=(uint16) scene;
3274 pages=(uint16) GetImageListLength(image);
3275 if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
3276 (image_info->adjoin != MagickFalse) && (pages > 1))
3277 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3278 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3280 (void) TIFFSetProperties(tiff,image,exception);
3282 (void) TIFFSetEXIFProperties(tiff,image,exception);
3284 Write image scanlines.
3286 if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3287 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3288 quantum_info->endian=LSBEndian;
3289 pixels=GetQuantumPixels(quantum_info);
3290 tiff_info.scanline=GetQuantumPixels(quantum_info);
3291 switch (photometric)
3293 case PHOTOMETRIC_CIELAB:
3294 case PHOTOMETRIC_YCBCR:
3295 case PHOTOMETRIC_RGB:
3300 switch (image_info->interlace)
3305 quantum_type=RGBQuantum;
3306 if (image->alpha_trait == BlendPixelTrait)
3307 quantum_type=RGBAQuantum;
3308 for (y=0; y < (ssize_t) image->rows; y++)
3310 register const Quantum
3313 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3314 if (p == (const Quantum *) NULL)
3316 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3317 quantum_type,pixels,exception);
3319 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3321 if (image->previous == (Image *) NULL)
3323 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3325 if (status == MagickFalse)
3331 case PlaneInterlace:
3332 case PartitionInterlace:
3335 Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
3337 for (y=0; y < (ssize_t) image->rows; y++)
3339 register const Quantum
3342 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3343 if (p == (const Quantum *) NULL)
3345 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3346 RedQuantum,pixels,exception);
3347 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3350 if (image->previous == (Image *) NULL)
3352 status=SetImageProgress(image,SaveImageTag,100,400);
3353 if (status == MagickFalse)
3356 for (y=0; y < (ssize_t) image->rows; y++)
3358 register const Quantum
3361 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3362 if (p == (const Quantum *) NULL)
3364 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3365 GreenQuantum,pixels,exception);
3366 if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3369 if (image->previous == (Image *) NULL)
3371 status=SetImageProgress(image,SaveImageTag,200,400);
3372 if (status == MagickFalse)
3375 for (y=0; y < (ssize_t) image->rows; y++)
3377 register const Quantum
3380 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3381 if (p == (const Quantum *) NULL)
3383 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3384 BlueQuantum,pixels,exception);
3385 if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3388 if (image->previous == (Image *) NULL)
3390 status=SetImageProgress(image,SaveImageTag,300,400);
3391 if (status == MagickFalse)
3394 if (image->alpha_trait == BlendPixelTrait)
3395 for (y=0; y < (ssize_t) image->rows; y++)
3397 register const Quantum
3400 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3401 if (p == (const Quantum *) NULL)
3403 length=ExportQuantumPixels(image,(CacheView *) NULL,
3404 quantum_info,AlphaQuantum,pixels,exception);
3405 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3408 if (image->previous == (Image *) NULL)
3410 status=SetImageProgress(image,SaveImageTag,400,400);
3411 if (status == MagickFalse)
3419 case PHOTOMETRIC_SEPARATED:
3424 quantum_type=CMYKQuantum;
3425 if (image->alpha_trait == BlendPixelTrait)
3426 quantum_type=CMYKAQuantum;
3427 if (image->colorspace != CMYKColorspace)
3428 (void) TransformImageColorspace(image,CMYKColorspace,exception);
3429 for (y=0; y < (ssize_t) image->rows; y++)
3431 register const Quantum
3434 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3435 if (p == (const Quantum *) NULL)
3437 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3438 quantum_type,pixels,exception);
3439 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3441 if (image->previous == (Image *) NULL)
3443 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3445 if (status == MagickFalse)
3451 case PHOTOMETRIC_PALETTE:
3459 Colormapped TIFF image.
3461 red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3462 green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3463 blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3464 if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3465 (blue == (uint16 *) NULL))
3466 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3468 Initialize TIFF colormap.
3470 (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3471 (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3472 (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3473 for (i=0; i < (ssize_t) image->colors; i++)
3475 red[i]=ScaleQuantumToShort(image->colormap[i].red);
3476 green[i]=ScaleQuantumToShort(image->colormap[i].green);
3477 blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3479 (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3480 red=(uint16 *) RelinquishMagickMemory(red);
3481 green=(uint16 *) RelinquishMagickMemory(green);
3482 blue=(uint16 *) RelinquishMagickMemory(blue);
3487 Convert PseudoClass packets to contiguous grayscale scanlines.
3489 quantum_type=IndexQuantum;
3490 if (image->alpha_trait == BlendPixelTrait)
3492 if (photometric != PHOTOMETRIC_PALETTE)
3493 quantum_type=GrayAlphaQuantum;
3495 quantum_type=IndexAlphaQuantum;
3498 if (photometric != PHOTOMETRIC_PALETTE)
3499 quantum_type=GrayQuantum;
3500 for (y=0; y < (ssize_t) image->rows; y++)
3502 register const Quantum
3505 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3506 if (p == (const Quantum *) NULL)
3508 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3509 quantum_type,pixels,exception);
3510 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3512 if (image->previous == (Image *) NULL)
3514 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3516 if (status == MagickFalse)
3523 quantum_info=DestroyQuantumInfo(quantum_info);
3524 if (image->colorspace == LabColorspace)
3525 DecodeLabImage(image,exception);
3526 DestroyTIFFInfo(&tiff_info);
3527 if (0 && (image_info->verbose == MagickTrue))
3528 TIFFPrintDirectory(tiff,stdout,MagickFalse);
3529 (void) TIFFWriteDirectory(tiff);
3530 image=SyncNextImageInList(image);
3531 if (image == (Image *) NULL)
3533 status=SetImageProgress(image,SaveImagesTag,scene++,
3534 GetImageListLength(image));
3535 if (status == MagickFalse)
3537 } while (image_info->adjoin != MagickFalse);
3538 (void) TIFFSetWarningHandler(warning_handler);
3539 (void) TIFFSetErrorHandler(error_handler);