2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % TTTTT IIIII FFFFF FFFFF %
13 % Read/Write TIFF Image Format %
20 % Copyright 1999-2011 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/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/color.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colorspace.h"
51 #include "MagickCore/colorspace-private.h"
52 #include "MagickCore/constitute.h"
53 #include "MagickCore/enhance.h"
54 #include "MagickCore/exception.h"
55 #include "MagickCore/exception-private.h"
56 #include "MagickCore/geometry.h"
57 #include "MagickCore/image.h"
58 #include "MagickCore/image-private.h"
59 #include "MagickCore/list.h"
60 #include "MagickCore/log.h"
61 #include "MagickCore/magick.h"
62 #include "MagickCore/memory_.h"
63 #include "MagickCore/module.h"
64 #include "MagickCore/monitor.h"
65 #include "MagickCore/monitor-private.h"
66 #include "MagickCore/option.h"
67 #include "MagickCore/pixel-accessor.h"
68 #include "MagickCore/property.h"
69 #include "MagickCore/quantum.h"
70 #include "MagickCore/quantum-private.h"
71 #include "MagickCore/profile.h"
72 #include "MagickCore/resize.h"
73 #include "MagickCore/resource_.h"
74 #include "MagickCore/semaphore.h"
75 #include "MagickCore/splay-tree.h"
76 #include "MagickCore/static.h"
77 #include "MagickCore/statistic.h"
78 #include "MagickCore/string_.h"
79 #include "MagickCore/string-private.h"
80 #include "MagickCore/thread_.h"
81 #include "MagickCore/utility.h"
82 #if defined(MAGICKCORE_TIFF_DELEGATE)
83 # if defined(MAGICKCORE_HAVE_TIFFCONF_H)
84 # include "tiffconf.h"
88 # if !defined(COMPRESSION_ADOBE_DEFLATE)
89 # define COMPRESSION_ADOBE_DEFLATE 8
91 # if !defined(PREDICTOR_HORIZONTAL)
92 # define PREDICTOR_HORIZONTAL 2
94 # if !defined(TIFFTAG_COPYRIGHT)
95 # define TIFFTAG_COPYRIGHT 33432
97 # if !defined(TIFFTAG_OPIIMAGEID)
98 # define TIFF_OPIIMAGEID 32781
102 Typedef declarations.
104 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
105 typedef struct _ExifInfo
115 static const ExifInfo
117 { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, "exif:ExposureTime" },
118 { EXIFTAG_FNUMBER, TIFF_RATIONAL, "exif:FNumber" },
119 { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, "exif:ExposureProgram" },
120 { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, "exif:SpectralSensitivity" },
121 { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, "exif:ISOSpeedRatings" },
122 { EXIFTAG_OECF, TIFF_NOTYPE, "exif:OptoelectricConversionFactor" },
123 { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, "exif:ExifVersion" },
124 { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, "exif:DateTimeOriginal" },
125 { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, "exif:DateTimeDigitized" },
126 { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, "exif:ComponentsConfiguration" },
127 { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, "exif:CompressedBitsPerPixel" },
128 { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, "exif:ShutterSpeedValue" },
129 { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, "exif:ApertureValue" },
130 { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, "exif:BrightnessValue" },
131 { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, "exif:ExposureBiasValue" },
132 { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, "exif:MaxApertureValue" },
133 { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, "exif:SubjectDistance" },
134 { EXIFTAG_METERINGMODE, TIFF_SHORT, "exif:MeteringMode" },
135 { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, "exif:LightSource" },
136 { EXIFTAG_FLASH, TIFF_SHORT, "exif:Flash" },
137 { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, "exif:FocalLength" },
138 { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, "exif:SubjectArea" },
139 { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, "exif:MakerNote" },
140 { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, "exif:UserComment" },
141 { EXIFTAG_SUBSECTIME, TIFF_ASCII, "exif:SubSecTime" },
142 { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, "exif:SubSecTimeOriginal" },
143 { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, "exif:SubSecTimeDigitized" },
144 { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, "exif:FlashpixVersion" },
145 { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, "exif:PixelXDimension" },
146 { EXIFTAG_PIXELXDIMENSION, TIFF_SHORT, "exif:PixelXDimension" },
147 { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, "exif:PixelYDimension" },
148 { EXIFTAG_PIXELYDIMENSION, TIFF_SHORT, "exif:PixelYDimension" },
149 { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, "exif:RelatedSoundFile" },
150 { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, "exif:FlashEnergy" },
151 { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, "exif:SpatialFrequencyResponse" },
152 { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneXResolution" },
153 { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneYResolution" },
154 { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, "exif:FocalPlaneResolutionUnit" },
155 { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, "exif:SubjectLocation" },
156 { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, "exif:ExposureIndex" },
157 { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, "exif:SensingMethod" },
158 { EXIFTAG_FILESOURCE, TIFF_NOTYPE, "exif:FileSource" },
159 { EXIFTAG_SCENETYPE, TIFF_NOTYPE, "exif:SceneType" },
160 { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, "exif:CFAPattern" },
161 { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, "exif:CustomRendered" },
162 { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, "exif:ExposureMode" },
163 { EXIFTAG_WHITEBALANCE, TIFF_SHORT, "exif:WhiteBalance" },
164 { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, "exif:DigitalZoomRatio" },
165 { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, "exif:FocalLengthIn35mmFilm" },
166 { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, "exif:SceneCaptureType" },
167 { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, "exif:GainControl" },
168 { EXIFTAG_CONTRAST, TIFF_SHORT, "exif:Contrast" },
169 { EXIFTAG_SATURATION, TIFF_SHORT, "exif:Saturation" },
170 { EXIFTAG_SHARPNESS, TIFF_SHORT, "exif:Sharpness" },
171 { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, "exif:DeviceSettingDescription" },
172 { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, "exif:SubjectDistanceRange" },
173 { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, "exif:ImageUniqueID" },
174 { 0, 0, (char *) NULL }
177 #endif /* MAGICKCORE_TIFF_DELEGATE */
182 static MagickThreadKey
186 *tiff_semaphore = (SemaphoreInfo *) NULL;
188 static volatile MagickBooleanType
189 instantiate_key = MagickFalse;
192 Forward declarations.
194 #if defined(MAGICKCORE_TIFF_DELEGATE)
196 ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
198 static MagickBooleanType
199 WriteGROUP4Image(const ImageInfo *,Image *,ExceptionInfo *),
200 WritePTIFImage(const ImageInfo *,Image *,ExceptionInfo *),
201 WriteTIFFImage(const ImageInfo *,Image *,ExceptionInfo *);
205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
215 % IsTIFF() returns MagickTrue if the image format type, identified by the
216 % magick string, is TIFF.
218 % The format of the IsTIFF method is:
220 % MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
222 % A description of each parameter follows:
224 % o magick: compare image format pattern against these bytes.
226 % o length: Specifies the length of the magick string.
229 static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
233 if (memcmp(magick,"\115\115\000\052",4) == 0)
235 if (memcmp(magick,"\111\111\052\000",4) == 0)
237 #if defined(TIFF_VERSION_BIG)
240 if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
242 if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
248 #if defined(MAGICKCORE_TIFF_DELEGATE)
250 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
254 % R e a d G R O U P 4 I m a g e %
258 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
260 % ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
261 % allocates the memory necessary for the new Image structure and returns a
262 % pointer to the new image.
264 % The format of the ReadGROUP4Image method is:
266 % Image *ReadGROUP4Image(const ImageInfo *image_info,
267 % ExceptionInfo *exception)
269 % A description of each parameter follows:
271 % o image_info: the image info.
273 % o exception: return any errors or warnings in this structure.
277 static inline size_t WriteLSBLong(FILE *file,const size_t value)
282 buffer[0]=(unsigned char) value;
283 buffer[1]=(unsigned char) (value >> 8);
284 buffer[2]=(unsigned char) (value >> 16);
285 buffer[3]=(unsigned char) (value >> 24);
286 return(fwrite(buffer,1,4,file));
289 static Image *ReadGROUP4Image(const ImageInfo *image_info,
290 ExceptionInfo *exception)
293 filename[MaxTextExtent];
321 assert(image_info != (const ImageInfo *) NULL);
322 assert(image_info->signature == MagickSignature);
323 if (image_info->debug != MagickFalse)
324 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
325 image_info->filename);
326 assert(exception != (ExceptionInfo *) NULL);
327 assert(exception->signature == MagickSignature);
328 image=AcquireImage(image_info,exception);
329 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
330 if (status == MagickFalse)
332 image=DestroyImageList(image);
333 return((Image *) NULL);
336 Write raw CCITT Group 4 wrapped as a TIFF image file.
339 unique_file=AcquireUniqueFileResource(filename);
340 if (unique_file != -1)
341 file=fdopen(unique_file,"wb");
342 if ((unique_file == -1) || (file == (FILE *) NULL))
343 ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
344 length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
345 length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
346 length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
347 length=WriteLSBLong(file,image->columns);
348 length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
349 length=WriteLSBLong(file,image->rows);
350 length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
351 length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
352 length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
353 length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
354 strip_offset=10+(12*14)+4+8;
355 length=WriteLSBLong(file,(size_t) strip_offset);
356 length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
357 length=WriteLSBLong(file,(size_t) image_info->orientation);
358 length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
359 length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
360 length=WriteLSBLong(file,image->rows);
361 length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
362 offset=(ssize_t) ftell(file)-4;
363 length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
364 length=WriteLSBLong(file,(size_t) (strip_offset-8));
365 length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
366 length=WriteLSBLong(file,(size_t) (strip_offset-8));
367 length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
368 length=fwrite("\000\000\000\000",1,4,file);
369 length=WriteLSBLong(file,(long) image->x_resolution);
370 length=WriteLSBLong(file,1);
371 for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
372 (void) fputc(c,file);
373 offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
374 length=WriteLSBLong(file,(unsigned int) length);
376 (void) CloseBlob(image);
377 image=DestroyImage(image);
381 read_info=CloneImageInfo((ImageInfo *) NULL);
382 (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
383 image=ReadTIFFImage(read_info,exception);
384 read_info=DestroyImageInfo(read_info);
385 if (image != (Image *) NULL)
387 (void) CopyMagickString(image->filename,image_info->filename,
389 (void) CopyMagickString(image->magick_filename,image_info->filename,
391 (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
393 (void) RelinquishUniqueFileResource(filename);
398 #if defined(MAGICKCORE_TIFF_DELEGATE)
400 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
404 % R e a d T I F F I m a g e %
408 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
410 % ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
411 % memory necessary for the new Image structure and returns a pointer to the
414 % The format of the ReadTIFFImage method is:
416 % Image *ReadTIFFImage(const ImageInfo *image_info,
417 % ExceptionInfo *exception)
419 % A description of each parameter follows:
421 % o image_info: the image info.
423 % o exception: return any errors or warnings in this structure.
427 static inline size_t MagickMax(const size_t x,const size_t y)
434 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
441 static MagickBooleanType ReadProfile(Image *image,const char *name,
442 unsigned char *datum,ssize_t length,ExceptionInfo *exception)
456 if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"xmp") != 0))
458 for (i=0; i < (length-4); i+=2)
459 if (LocaleNCompare((char *) (datum+i),"8BIM",4) == 0)
468 profile=BlobToStringInfo(datum+i,(size_t) length);
469 if (profile == (StringInfo *) NULL)
470 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
472 status=SetImageProfile(image,name,profile);
473 profile=DestroyStringInfo(profile);
474 if (status == MagickFalse)
475 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
480 #if defined(__cplusplus) || defined(c_plusplus)
484 static int TIFFCloseBlob(thandle_t image)
486 (void) CloseBlob((Image *) image);
490 static void TIFFErrors(const char *module,const char *format,va_list error)
493 message[MaxTextExtent];
498 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
499 (void) vsnprintf(message,MaxTextExtent,format,error);
501 (void) vsprintf(message,format,error);
503 (void) ConcatenateMagickString(message,".",MaxTextExtent);
504 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
505 if (exception != (ExceptionInfo *) NULL)
506 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
510 static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
518 #if defined(TIFFTAG_ICCPROFILE)
520 if (TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1)
521 (void) ReadProfile(image,"icc",profile,(ssize_t) length,exception);
523 #if defined(TIFFTAG_PHOTOSHOP)
525 if (TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1)
526 (void) ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
528 #if defined(TIFFTAG_RICHTIFFIPTC)
530 if (TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1)
532 if (TIFFIsByteSwapped(tiff) != 0)
533 TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
534 (void) ReadProfile(image,"iptc",profile,4L*length,exception);
537 #if defined(TIFFTAG_XMLPACKET)
539 if (TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1)
540 (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
543 if (TIFFGetField(tiff,37724,&length,&profile) == 1)
544 (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
547 static void TIFFGetProperties(TIFF *tiff,Image *image)
550 message[MaxTextExtent],
556 if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
557 (void) SetImageProperty(image,"tiff:artist",text);
558 if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
559 (void) SetImageProperty(image,"tiff:copyright",text);
560 if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
561 (void) SetImageProperty(image,"tiff:timestamp",text);
562 if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
563 (void) SetImageProperty(image,"tiff:document",text);
564 if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
565 (void) SetImageProperty(image,"tiff:hostcomputer",text);
566 if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
567 (void) SetImageProperty(image,"comment",text);
568 if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
569 (void) SetImageProperty(image,"tiff:make",text);
570 if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
571 (void) SetImageProperty(image,"tiff:model",text);
572 if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
574 if (count >= MaxTextExtent)
575 count=MaxTextExtent-1;
576 (void) CopyMagickString(message,text,count+1);
577 (void) SetImageProperty(image,"tiff:image-id",message);
579 if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
580 (void) SetImageProperty(image,"label",text);
581 if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
582 (void) SetImageProperty(image,"tiff:software",text);
583 if (TIFFGetField(tiff,33423,&count,&text) == 1)
585 if (count >= MaxTextExtent)
586 count=MaxTextExtent-1;
587 (void) CopyMagickString(message,text,count+1);
588 (void) SetImageProperty(image,"tiff:kodak-33423",message);
590 if (TIFFGetField(tiff,36867,&count,&text) == 1)
592 if (count >= MaxTextExtent)
593 count=MaxTextExtent-1;
594 (void) CopyMagickString(message,text,count+1);
595 (void) SetImageProperty(image,"tiff:kodak-36867",message);
599 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
601 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
603 value[MaxTextExtent];
618 Read EXIF properties.
620 if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) == 0)
622 directory=TIFFCurrentDirectory(tiff);
623 if (TIFFReadEXIFDirectory(tiff,offset) == 0)
626 for (i=0; exif_info[i].tag != 0; i++)
629 switch (exif_info[i].type)
637 if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans) != 0) &&
638 (ascii != (char *) NULL) && (*ascii != '\0'))
639 (void) CopyMagickMemory(value,ascii,MaxTextExtent);
647 if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans) != 0)
648 (void) FormatLocaleString(value,MaxTextExtent,"%d",(int) shorty[0]);
656 if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans) != 0)
657 (void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
668 if (TIFFGetField(tiff,exif_info[i].tag,&rational,&sans) != 0)
669 (void) FormatLocaleString(value,MaxTextExtent,"%g",rational[0]);
676 (void) SetImageProperty(image,exif_info[i].property,value);
678 TIFFSetDirectory(tiff,directory);
685 static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
687 *base=(tdata_t *) GetBlobStreamData((Image *) image);
688 if (*base != (tdata_t *) NULL)
689 *size=(toff_t) GetBlobSize((Image *) image);
690 if (*base != (tdata_t *) NULL)
695 static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
700 count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
701 (unsigned char *) data);
705 static int32 TIFFReadPixels(TIFF *tiff,size_t bits_per_sample,
706 tsample_t sample,ssize_t row,tdata_t scanline)
711 (void) bits_per_sample;
712 status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
716 static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
718 return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
721 static toff_t TIFFGetBlobSize(thandle_t image)
723 return((toff_t) GetBlobSize((Image *) image));
726 static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
733 static void TIFFWarnings(const char *module,const char *format,va_list warning)
736 message[MaxTextExtent];
741 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
742 (void) vsnprintf(message,MaxTextExtent,format,warning);
744 (void) vsprintf(message,format,warning);
746 (void) ConcatenateMagickString(message,".",MaxTextExtent);
747 exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
748 if (exception != (ExceptionInfo *) NULL)
749 (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
750 message,"`%s'",module);
753 static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
758 count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
759 (unsigned char *) data);
763 #if defined(__cplusplus) || defined(c_plusplus)
767 static Image *ReadTIFFImage(const ImageInfo *image_info,
768 ExceptionInfo *exception)
772 ReadSingleSampleMethod,
856 assert(image_info != (const ImageInfo *) NULL);
857 assert(image_info->signature == MagickSignature);
858 if (image_info->debug != MagickFalse)
859 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
860 image_info->filename);
861 assert(exception != (ExceptionInfo *) NULL);
862 assert(exception->signature == MagickSignature);
863 image=AcquireImage(image_info,exception);
864 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
865 if (status == MagickFalse)
867 image=DestroyImageList(image);
868 return((Image *) NULL);
870 (void) MagickSetThreadValue(tiff_exception,exception);
871 error_handler=TIFFSetErrorHandler(TIFFErrors);
872 warning_handler=TIFFSetWarningHandler(TIFFWarnings);
873 tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
874 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
876 if (tiff == (TIFF *) NULL)
878 (void) TIFFSetWarningHandler(warning_handler);
879 (void) TIFFSetErrorHandler(error_handler);
880 image=DestroyImageList(image);
881 return((Image *) NULL);
883 debug=IsEventLogging();
885 if (image_info->number_scenes != 0)
888 Generate blank images for subimage specification (e.g. image.tif[4].
890 for (i=0; i < (ssize_t) image_info->scene; i++)
892 (void) TIFFReadDirectory(tiff);
893 AcquireNextImage(image_info,image,exception);
894 if (GetNextImageInList(image) == (Image *) NULL)
896 image=DestroyImageList(image);
897 return((Image *) NULL);
899 image=SyncNextImageInList(image);
904 if (0 && (image_info->verbose != MagickFalse))
905 TIFFPrintDirectory(tiff,stdout,MagickFalse);
906 TIFFGetEXIFProperties(tiff,image);
907 TIFFGetProfiles(tiff,image,exception);
908 TIFFGetProperties(tiff,image);
909 (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
911 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag);
912 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation);
913 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGEWIDTH,&width);
914 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_IMAGELENGTH,&height);
915 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
916 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace);
917 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample);
918 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format);
919 if (sample_format == SAMPLEFORMAT_IEEEFP)
920 (void) SetImageProperty(image,"quantum:format","floating-point");
921 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value);
922 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value);
923 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric);
926 case PHOTOMETRIC_MINISBLACK:
928 (void) SetImageProperty(image,"tiff:photometric","min-is-black");
931 case PHOTOMETRIC_MINISWHITE:
933 (void) SetImageProperty(image,"tiff:photometric","min-is-white");
936 case PHOTOMETRIC_PALETTE:
938 (void) SetImageProperty(image,"tiff:photometric","palette");
941 case PHOTOMETRIC_RGB:
943 (void) SetImageProperty(image,"tiff:photometric","RGB");
946 case PHOTOMETRIC_CIELAB:
948 (void) SetImageProperty(image,"tiff:photometric","CIELAB");
951 case PHOTOMETRIC_SEPARATED:
953 (void) SetImageProperty(image,"tiff:photometric","separated");
956 case PHOTOMETRIC_YCBCR:
958 (void) SetImageProperty(image,"tiff:photometric","YCBCR");
963 (void) SetImageProperty(image,"tiff:photometric","unknown");
967 if (image->debug != MagickFalse)
969 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
970 (unsigned int) width,(unsigned int) height);
971 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
973 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
974 "Bits per sample: %u",bits_per_sample);
975 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
976 "Min sample value: %u",min_sample_value);
977 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
978 "Max sample value: %u",max_sample_value);
979 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
980 "interpretation: %s",GetImageProperty(image,"tiff:photometric"));
982 image->columns=(size_t) width;
983 image->rows=(size_t) height;
984 image->depth=(size_t) bits_per_sample;
985 if (image->debug != MagickFalse)
986 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
987 (double) image->depth);
989 image->endian=MSBEndian;
990 if ((int) (*(char *) &lsb_first) != 0)
991 image->endian=LSBEndian;
992 if (photometric == PHOTOMETRIC_SEPARATED)
993 image->colorspace=CMYKColorspace;
994 if (photometric == PHOTOMETRIC_CIELAB)
995 image->colorspace=LabColorspace;
996 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
998 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
999 x_resolution=(float) image->x_resolution;
1000 y_resolution=(float) image->y_resolution;
1001 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution);
1002 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
1003 image->x_resolution=x_resolution;
1004 image->y_resolution=y_resolution;
1005 x_position=(float) image->page.x/x_resolution;
1006 y_position=(float) image->page.y/y_resolution;
1007 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
1008 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
1009 image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
1010 image->page.y=(ssize_t) ceil(y_position*y_resolution-0.5);
1011 image->orientation=(OrientationType) orientation;
1012 chromaticity=(float *) NULL;
1013 (void) TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity);
1014 if (chromaticity != (float *) NULL)
1016 image->chromaticity.white_point.x=chromaticity[0];
1017 image->chromaticity.white_point.y=chromaticity[1];
1019 chromaticity=(float *) NULL;
1020 (void) TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity);
1021 if (chromaticity != (float *) NULL)
1023 image->chromaticity.red_primary.x=chromaticity[0];
1024 image->chromaticity.red_primary.y=chromaticity[1];
1025 image->chromaticity.green_primary.x=chromaticity[2];
1026 image->chromaticity.green_primary.y=chromaticity[3];
1027 image->chromaticity.blue_primary.x=chromaticity[4];
1028 image->chromaticity.blue_primary.y=chromaticity[5];
1031 Allocate memory for the image and pixel buffer.
1033 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
1034 if ((compress_tag != COMPRESSION_NONE) &&
1035 (TIFFIsCODECConfigured(compress_tag) == 0))
1038 ThrowReaderException(CoderError,"CompressNotSupported");
1041 switch (compress_tag)
1043 case COMPRESSION_NONE: image->compression=NoCompression; break;
1044 case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
1045 case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
1046 case COMPRESSION_JPEG:
1048 image->compression=JPEGCompression;
1049 #if defined(JPEG_SUPPORT)
1052 sampling_factor[MaxTextExtent];
1058 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
1059 &horizontal,&vertical);
1060 (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
1061 horizontal,vertical);
1062 (void) SetImageProperty(image,"jpeg:sampling-factor",
1064 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1065 "Sampling Factors: %s",sampling_factor);
1066 if ((samples_per_pixel > 1) && (photometric == PHOTOMETRIC_YCBCR))
1068 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,
1070 photometric=PHOTOMETRIC_RGB;
1076 case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
1077 #if defined(COMPRESSION_LZMA)
1078 case COMPRESSION_LZMA: image->compression=LZMACompression; break;
1080 case COMPRESSION_LZW: image->compression=LZWCompression; break;
1081 case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
1082 case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
1083 default: image->compression=RLECompression; break;
1085 quantum_info=AcquireQuantumInfo(image_info,image);
1086 if (quantum_info == (QuantumInfo *) NULL)
1089 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1091 if (sample_format == SAMPLEFORMAT_UINT)
1092 status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
1093 if (sample_format == SAMPLEFORMAT_INT)
1094 status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
1095 if (sample_format == SAMPLEFORMAT_IEEEFP)
1096 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
1097 if (status == MagickFalse)
1100 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1103 switch (photometric)
1105 case PHOTOMETRIC_MINISBLACK:
1107 quantum_info->min_is_white=MagickFalse;
1110 case PHOTOMETRIC_MINISWHITE:
1112 quantum_info->min_is_white=MagickTrue;
1118 associated_alpha=MagickFalse;
1120 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
1122 if (extra_samples == 0)
1124 if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
1125 image->matte=MagickTrue;
1128 for (i=0; i < extra_samples; i++)
1130 image->matte=MagickTrue;
1131 if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
1132 SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
1134 option=GetImageOption(image_info,"tiff:alpha");
1135 if (option != (const char *) NULL)
1136 associated_alpha=LocaleCompare(option,"associated") == 0 ? MagickTrue :
1138 if (image->matte != MagickFalse)
1139 (void) SetImageProperty(image,"tiff:alpha",
1140 associated_alpha != MagickFalse ? "associated" : "unassociated");
1141 if ((photometric == PHOTOMETRIC_PALETTE) &&
1142 (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
1147 colors=(size_t) GetQuantumRange(bits_per_sample)+1;
1148 if (AcquireImageColormap(image,colors,exception) == MagickFalse)
1151 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1154 if (units == RESUNIT_INCH)
1155 image->units=PixelsPerInchResolution;
1156 if (units == RESUNIT_CENTIMETER)
1157 image->units=PixelsPerCentimeterResolution;
1158 value=(unsigned short) image->scene;
1159 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages);
1161 if (image_info->ping != MagickFalse)
1163 if (image_info->number_scenes != 0)
1164 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1166 goto next_tiff_frame;
1168 method=ReadGenericMethod;
1169 if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) != 0)
1172 value[MaxTextExtent];
1174 method=ReadStripMethod;
1175 (void) FormatLocaleString(value,MaxTextExtent,"%u",
1176 (unsigned int) rows_per_strip);
1177 (void) SetImageProperty(image,"tiff:rows-per-strip",value);
1179 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
1180 method=ReadRGBAMethod;
1181 if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
1182 method=ReadCMYKAMethod;
1183 if ((photometric != PHOTOMETRIC_RGB) &&
1184 (photometric != PHOTOMETRIC_CIELAB) &&
1185 (photometric != PHOTOMETRIC_SEPARATED))
1186 method=ReadGenericMethod;
1187 if (image->storage_class == PseudoClass)
1188 method=ReadSingleSampleMethod;
1189 if ((photometric == PHOTOMETRIC_MINISBLACK) ||
1190 (photometric == PHOTOMETRIC_MINISWHITE))
1191 method=ReadSingleSampleMethod;
1192 if ((photometric != PHOTOMETRIC_SEPARATED) &&
1193 (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
1194 method=ReadGenericMethod;
1195 if (image->compression == JPEGCompression)
1196 method=ReadGenericMethod;
1197 if (TIFFIsTiled(tiff) != MagickFalse)
1198 method=ReadTileMethod;
1199 quantum_type=RGBQuantum;
1200 pixels=GetQuantumPixels(quantum_info);
1203 case ReadSingleSampleMethod:
1206 Convert TIFF image to PseudoClass MIFF image.
1208 if ((image->storage_class == PseudoClass) &&
1209 (photometric == PHOTOMETRIC_PALETTE))
1220 Initialize colormap.
1222 (void) TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
1223 &green_colormap,&blue_colormap);
1224 range=255; /* might be old style 8-bit colormap */
1225 for (i=0; i < (ssize_t) image->colors; i++)
1226 if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
1227 (blue_colormap[i] >= 256))
1232 for (i=0; i < (ssize_t) image->colors; i++)
1234 image->colormap[i].red=ClampToQuantum(((double) QuantumRange*
1235 red_colormap[i])/range);
1236 image->colormap[i].green=ClampToQuantum(((double) QuantumRange*
1237 green_colormap[i])/range);
1238 image->colormap[i].blue=ClampToQuantum(((double) QuantumRange*
1239 blue_colormap[i])/range);
1242 quantum_type=IndexQuantum;
1243 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1244 if (image->matte != MagickFalse)
1246 if (image->storage_class != PseudoClass)
1248 quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
1250 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1254 quantum_type=IndexAlphaQuantum;
1255 pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0);
1259 if (image->storage_class != PseudoClass)
1261 quantum_type=GrayQuantum;
1262 pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
1264 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1265 if (status == MagickFalse)
1268 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1270 pixels=GetQuantumPixels(quantum_info);
1271 for (y=0; y < (ssize_t) image->rows; y++)
1279 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1282 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1283 if (q == (Quantum *) NULL)
1285 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1286 quantum_type,pixels,exception);
1288 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1290 if (image->previous == (Image *) NULL)
1292 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1294 if (status == MagickFalse)
1300 case ReadRGBAMethod:
1303 Convert TIFF image to DirectClass MIFF image.
1305 pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
1306 quantum_type=RGBQuantum;
1307 if (image->matte != MagickFalse)
1309 quantum_type=RGBAQuantum;
1310 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1312 if (image->colorspace == CMYKColorspace)
1314 pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
1315 quantum_type=CMYKQuantum;
1316 if (image->matte != MagickFalse)
1318 quantum_type=CMYKAQuantum;
1319 pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
1322 status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
1323 if (status == MagickFalse)
1326 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1328 pixels=GetQuantumPixels(quantum_info);
1329 for (y=0; y < (ssize_t) image->rows; y++)
1337 status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
1340 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1341 if (q == (Quantum *) NULL)
1343 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1344 quantum_type,pixels,exception);
1345 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1347 if (image->previous == (Image *) NULL)
1349 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1351 if (status == MagickFalse)
1357 case ReadCMYKAMethod:
1360 Convert TIFF image to DirectClass MIFF image.
1362 for (i=0; i < (ssize_t) samples_per_pixel; i++)
1364 for (y=0; y < (ssize_t) image->rows; y++)
1372 status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
1376 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
1377 if (q == (Quantum *) NULL)
1379 if (image->colorspace != CMYKColorspace)
1382 case 0: quantum_type=RedQuantum; break;
1383 case 1: quantum_type=GreenQuantum; break;
1384 case 2: quantum_type=BlueQuantum; break;
1385 case 3: quantum_type=AlphaQuantum; break;
1386 default: quantum_type=UndefinedQuantum; break;
1391 case 0: quantum_type=CyanQuantum; break;
1392 case 1: quantum_type=MagentaQuantum; break;
1393 case 2: quantum_type=YellowQuantum; break;
1394 case 3: quantum_type=BlackQuantum; break;
1395 case 4: quantum_type=AlphaQuantum; break;
1396 default: quantum_type=UndefinedQuantum; break;
1398 length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1399 quantum_type,pixels,exception);
1400 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1403 if (image->previous == (Image *) NULL)
1405 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1407 if (status == MagickFalse)
1413 case ReadStripMethod:
1415 register unsigned char
1419 Convert stripped TIFF image to DirectClass MIFF image.
1422 p=(unsigned char *) NULL;
1423 for (y=0; y < (ssize_t) image->rows; y++)
1431 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1432 if (q == (Quantum *) NULL)
1436 if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
1438 i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
1442 p=(unsigned char *) (((uint32 *) pixels)+image->columns*i);
1443 for (x=0; x < (ssize_t) image->columns; x++)
1445 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1447 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1449 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1451 if (image->matte != MagickFalse)
1452 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1455 q+=GetPixelChannels(image);
1457 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1459 if (image->previous == (Image *) NULL)
1461 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1463 if (status == MagickFalse)
1469 case ReadTileMethod:
1483 Convert tiled TIFF image to DirectClass MIFF image.
1485 if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) == 0) ||
1486 (TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) == 0))
1489 ThrowReaderException(CoderError,"ImageIsNotTiled");
1491 (void) SetImageStorageClass(image,DirectClass,&image->exception);
1492 number_pixels=columns*rows;
1493 tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
1494 sizeof(*tile_pixels));
1495 if (tile_pixels == (uint32 *) NULL)
1498 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1500 for (y=0; y < (ssize_t) image->rows; y+=rows)
1513 rows_remaining=image->rows-y;
1514 if ((ssize_t) (y+rows) < (ssize_t) image->rows)
1515 rows_remaining=rows;
1516 tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
1518 if (tile == (Quantum *) NULL)
1520 for (x=0; x < (ssize_t) image->columns; x+=columns)
1526 if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
1528 columns_remaining=image->columns-x;
1529 if ((ssize_t) (x+columns) < (ssize_t) image->columns)
1530 columns_remaining=columns;
1531 p=tile_pixels+(rows-rows_remaining)*columns;
1532 q=tile+GetPixelChannels(image)*(image->columns*(rows_remaining-1)+
1534 for (row=rows_remaining; row > 0; row--)
1536 if (image->matte != MagickFalse)
1537 for (column=columns_remaining; column > 0; column--)
1539 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1541 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1543 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1545 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1548 q+=GetPixelChannels(image);
1551 for (column=columns_remaining; column > 0; column--)
1553 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1555 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1557 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1560 q+=GetPixelChannels(image);
1562 p+=columns-columns_remaining;
1563 q-=GetPixelChannels(image)*(image->columns+columns_remaining);
1566 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1568 if (image->previous == (Image *) NULL)
1570 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1572 if (status == MagickFalse)
1576 tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
1579 case ReadGenericMethod:
1589 Convert TIFF image to DirectClass MIFF image.
1591 number_pixels=(MagickSizeType) image->columns*image->rows;
1592 if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
1593 (number_pixels*sizeof(uint32))))
1596 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1598 pixels=(uint32 *) AcquireQuantumMemory(image->columns,image->rows*
1600 if (pixels == (uint32 *) NULL)
1603 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1605 (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
1606 (uint32) image->rows,(uint32 *) pixels,0);
1608 Convert image to DirectClass pixel packets.
1610 p=pixels+number_pixels-1;
1611 for (y=0; y < (ssize_t) image->rows; y++)
1619 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
1620 if (q == (Quantum *) NULL)
1622 q+=GetPixelChannels(image)*(image->columns-1);
1623 for (x=0; x < (ssize_t) image->columns; x++)
1625 SetPixelRed(image,ScaleCharToQuantum((unsigned char)
1627 SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
1629 SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
1631 if (image->matte != MagickFalse)
1632 SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
1635 q-=GetPixelChannels(image);;
1637 if (SyncAuthenticPixels(image,exception) == MagickFalse)
1639 if (image->previous == (Image *) NULL)
1641 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
1643 if (status == MagickFalse)
1647 pixels=(uint32 *) RelinquishMagickMemory(pixels);
1651 SetQuantumImageType(image,quantum_type);
1653 if ((photometric == PHOTOMETRIC_LOGL) ||
1654 (photometric == PHOTOMETRIC_MINISBLACK) ||
1655 (photometric == PHOTOMETRIC_MINISWHITE))
1657 image->type=GrayscaleType;
1658 if (bits_per_sample == 1)
1659 image->type=BilevelType;
1661 if (image->storage_class == PseudoClass)
1662 image->depth=GetImageDepth(image,exception);
1663 image->endian=MSBEndian;
1664 if (endian == FILLORDER_LSB2MSB)
1665 image->endian=LSBEndian;
1666 if ((photometric == PHOTOMETRIC_LOGL) ||
1667 (photometric == PHOTOMETRIC_MINISBLACK) ||
1668 (photometric == PHOTOMETRIC_MINISWHITE))
1670 image->type=GrayscaleType;
1671 if (bits_per_sample == 1)
1672 image->type=BilevelType;
1675 Proceed to next image.
1677 if (image_info->number_scenes != 0)
1678 if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1680 status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
1681 if (status == MagickTrue)
1684 Allocate next image structure.
1686 AcquireNextImage(image_info,image,exception);
1687 if (GetNextImageInList(image) == (Image *) NULL)
1689 image=DestroyImageList(image);
1690 return((Image *) NULL);
1692 image=SyncNextImageInList(image);
1693 status=SetImageProgress(image,LoadImagesTag,image->scene-1,
1695 if (status == MagickFalse)
1698 quantum_info=DestroyQuantumInfo(quantum_info);
1699 } while (status == MagickTrue);
1700 (void) TIFFSetWarningHandler(warning_handler);
1701 (void) TIFFSetErrorHandler(error_handler);
1703 return(GetFirstImageInList(image));
1708 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1712 % R e g i s t e r T I F F I m a g e %
1716 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1718 % RegisterTIFFImage() adds properties for the TIFF image format to
1719 % the list of supported formats. The properties include the image format
1720 % tag, a method to read and/or write the format, whether the format
1721 % supports the saving of more than one frame to the same file or blob,
1722 % whether the format supports native in-memory I/O, and a brief
1723 % description of the format.
1725 % The format of the RegisterTIFFImage method is:
1727 % size_t RegisterTIFFImage(void)
1730 ModuleExport size_t RegisterTIFFImage(void)
1732 #define TIFFDescription "Tagged Image File Format"
1735 version[MaxTextExtent];
1740 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1741 tiff_semaphore=AllocateSemaphoreInfo();
1742 LockSemaphoreInfo(tiff_semaphore);
1743 if (instantiate_key == MagickFalse)
1745 if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
1746 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1747 instantiate_key=MagickTrue;
1749 UnlockSemaphoreInfo(tiff_semaphore);
1751 #if defined(TIFF_VERSION)
1752 (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
1754 #if defined(MAGICKCORE_TIFF_DELEGATE)
1763 for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
1769 entry=SetMagickInfo("GROUP4");
1770 #if defined(MAGICKCORE_TIFF_DELEGATE)
1771 entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
1772 entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
1774 entry->raw=MagickTrue;
1775 entry->endian_support=MagickTrue;
1776 entry->adjoin=MagickFalse;
1777 entry->format_type=ImplicitFormatType;
1778 entry->seekable_stream=MagickTrue;
1779 entry->thread_support=NoThreadSupport;
1780 entry->description=ConstantString("Raw CCITT Group4");
1781 entry->module=ConstantString("TIFF");
1782 (void) RegisterMagickInfo(entry);
1783 entry=SetMagickInfo("PTIF");
1784 #if defined(MAGICKCORE_TIFF_DELEGATE)
1785 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1786 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1788 entry->endian_support=MagickTrue;
1789 entry->seekable_stream=MagickTrue;
1790 entry->thread_support=NoThreadSupport;
1791 entry->description=ConstantString("Pyramid encoded TIFF");
1792 entry->module=ConstantString("TIFF");
1793 (void) RegisterMagickInfo(entry);
1794 entry=SetMagickInfo("TIF");
1795 #if defined(MAGICKCORE_TIFF_DELEGATE)
1796 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1797 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1799 entry->endian_support=MagickTrue;
1800 entry->seekable_stream=MagickTrue;
1801 entry->stealth=MagickTrue;
1802 entry->thread_support=NoThreadSupport;
1803 entry->description=ConstantString(TIFFDescription);
1804 if (*version != '\0')
1805 entry->version=ConstantString(version);
1806 entry->module=ConstantString("TIFF");
1807 (void) RegisterMagickInfo(entry);
1808 entry=SetMagickInfo("TIFF");
1809 #if defined(MAGICKCORE_TIFF_DELEGATE)
1810 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1811 entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
1813 entry->magick=(IsImageFormatHandler *) IsTIFF;
1814 entry->endian_support=MagickTrue;
1815 entry->seekable_stream=MagickTrue;
1816 entry->thread_support=NoThreadSupport;
1817 entry->description=ConstantString(TIFFDescription);
1818 if (*version != '\0')
1819 entry->version=ConstantString(version);
1820 entry->module=ConstantString("TIFF");
1821 (void) RegisterMagickInfo(entry);
1822 entry=SetMagickInfo("TIFF64");
1823 #if defined(TIFF_VERSION_BIG)
1824 entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
1825 entry->encoder=(EncodeImageHandler *) WritePTIFImage;
1827 entry->adjoin=MagickFalse;
1828 entry->endian_support=MagickTrue;
1829 entry->seekable_stream=MagickTrue;
1830 entry->thread_support=NoThreadSupport;
1831 entry->description=ConstantString("Tagged Image File Format (64-bit)");
1832 if (*version != '\0')
1833 entry->version=ConstantString(version);
1834 entry->module=ConstantString("TIFF");
1835 (void) RegisterMagickInfo(entry);
1836 return(MagickImageCoderSignature);
1840 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1844 % U n r e g i s t e r T I F F I m a g e %
1848 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1850 % UnregisterTIFFImage() removes format registrations made by the TIFF module
1851 % from the list of supported formats.
1853 % The format of the UnregisterTIFFImage method is:
1855 % UnregisterTIFFImage(void)
1858 ModuleExport void UnregisterTIFFImage(void)
1860 (void) UnregisterMagickInfo("RAWGROUP4");
1861 (void) UnregisterMagickInfo("PTIF");
1862 (void) UnregisterMagickInfo("TIF");
1863 (void) UnregisterMagickInfo("TIFF");
1864 (void) UnregisterMagickInfo("TIFF64");
1865 if (tiff_semaphore == (SemaphoreInfo *) NULL)
1866 tiff_semaphore=AllocateSemaphoreInfo();
1867 LockSemaphoreInfo(tiff_semaphore);
1868 if (instantiate_key != MagickFalse)
1869 if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
1870 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1871 instantiate_key=MagickFalse;
1872 UnlockSemaphoreInfo(tiff_semaphore);
1873 DestroySemaphoreInfo(&tiff_semaphore);
1876 #if defined(MAGICKCORE_TIFF_DELEGATE)
1878 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1882 % W r i t e G R O U P 4 I m a g e %
1886 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1888 % WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
1890 % The format of the WriteGROUP4Image method is:
1892 % MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
1893 % Image *image,ExceptionInfo *)
1895 % A description of each parameter follows:
1897 % o image_info: the image info.
1899 % o image: The image.
1901 % o exception: return any errors or warnings in this structure.
1904 static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
1905 Image *image,ExceptionInfo *exception)
1908 filename[MaxTextExtent];
1942 Write image as CCITT Group4 TIFF image to a temporary file.
1944 assert(image_info != (const ImageInfo *) NULL);
1945 assert(image_info->signature == MagickSignature);
1946 assert(image != (Image *) NULL);
1947 assert(image->signature == MagickSignature);
1948 if (image->debug != MagickFalse)
1949 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1950 assert(exception != (ExceptionInfo *) NULL);
1951 assert(exception->signature == MagickSignature);
1952 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1953 if (status == MagickFalse)
1955 huffman_image=CloneImage(image,0,0,MagickTrue,exception);
1956 if (huffman_image == (Image *) NULL)
1958 (void) CloseBlob(image);
1959 return(MagickFalse);
1961 huffman_image->endian=MSBEndian;
1963 unique_file=AcquireUniqueFileResource(filename);
1964 if (unique_file != -1)
1965 file=fdopen(unique_file,"wb");
1966 if ((unique_file == -1) || (file == (FILE *) NULL))
1968 ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
1970 return(MagickFalse);
1972 (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
1974 (void) SetImageType(huffman_image,BilevelType,exception);
1975 write_info=CloneImageInfo((ImageInfo *) NULL);
1976 SetImageInfoFile(write_info,file);
1977 write_info->compression=Group4Compression;
1978 write_info->type=BilevelType;
1979 (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
1980 status=WriteTIFFImage(write_info,huffman_image,exception);
1981 (void) fflush(file);
1982 write_info=DestroyImageInfo(write_info);
1983 if (status == MagickFalse)
1985 huffman_image=DestroyImage(huffman_image);
1986 (void) fclose(file);
1987 (void) RelinquishUniqueFileResource(filename);
1988 return(MagickFalse);
1990 tiff=TIFFOpen(filename,"rb");
1991 if (tiff == (TIFF *) NULL)
1993 huffman_image=DestroyImage(huffman_image);
1994 (void) fclose(file);
1995 (void) RelinquishUniqueFileResource(filename);
1996 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
1997 image_info->filename);
1998 return(MagickFalse);
2001 Allocate raw strip buffer.
2003 if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
2006 huffman_image=DestroyImage(huffman_image);
2007 (void) fclose(file);
2008 (void) RelinquishUniqueFileResource(filename);
2009 return(MagickFalse);
2011 strip_size=byte_count[0];
2012 for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2013 if (byte_count[i] > strip_size)
2014 strip_size=byte_count[i];
2015 buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
2017 if (buffer == (unsigned char *) NULL)
2020 huffman_image=DestroyImage(huffman_image);
2021 (void) fclose(file);
2022 (void) RelinquishUniqueFileResource(filename);
2023 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2024 image_info->filename);
2027 Compress runlength encoded to 2D Huffman pixels.
2029 for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
2031 count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
2032 if (WriteBlob(image,(size_t) count,buffer) != count)
2035 buffer=(unsigned char *) RelinquishMagickMemory(buffer);
2037 huffman_image=DestroyImage(huffman_image);
2038 (void) fclose(file);
2039 (void) RelinquishUniqueFileResource(filename);
2040 (void) CloseBlob(image);
2045 #if defined(MAGICKCORE_TIFF_DELEGATE)
2047 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2051 % W r i t e P T I F I m a g e %
2055 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2057 % WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
2060 % The format of the WritePTIFImage method is:
2062 % MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2063 % Image *image,ExceptionInfo *exception)
2065 % A description of each parameter follows:
2067 % o image_info: the image info.
2069 % o image: The image.
2071 % o exception: return any errors or warnings in this structure.
2074 static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
2075 Image *image,ExceptionInfo *exception)
2093 Create pyramid-encoded TIFF image.
2095 images=NewImageList();
2096 for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
2098 AppendImageToList(&images,CloneImage(next,0,0,MagickFalse,exception));
2099 columns=next->columns;
2101 while ((columns > 64) && (rows > 64))
2105 pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur,
2107 AppendImageToList(&images,pyramid_image);
2111 Write pyramid-encoded TIFF image.
2113 write_info=CloneImageInfo(image_info);
2114 *write_info->magick='\0';
2115 write_info->adjoin=MagickTrue;
2116 status=WriteTIFFImage(write_info,GetFirstImageInList(images),exception);
2117 images=DestroyImageList(images);
2118 write_info=DestroyImageInfo(write_info);
2123 #if defined(MAGICKCORE_TIFF_DELEGATE)
2125 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2128 % W r i t e T I F F I m a g e %
2132 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2134 % WriteTIFFImage() writes an image in the Tagged image file format.
2136 % The format of the WriteTIFFImage method is:
2138 % MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2139 % Image *image,ExceptionInfo *exception)
2141 % A description of each parameter follows:
2143 % o image_info: the image info.
2145 % o image: The image.
2147 % o exception: return any errors or warnings in this structure.
2151 typedef struct _TIFFInfo
2162 static void DestroyTIFFInfo(TIFFInfo *tiff_info)
2164 assert(tiff_info != (TIFFInfo *) NULL);
2165 if (tiff_info->scanlines != (unsigned char *) NULL)
2166 tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
2167 tiff_info->scanlines);
2168 if (tiff_info->pixels != (unsigned char *) NULL)
2169 tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
2173 static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
2174 TIFFInfo *tiff_info)
2186 assert(tiff_info != (TIFFInfo *) NULL);
2187 (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
2188 option=GetImageOption(image_info,"tiff:tile-geometry");
2189 if (option == (const char *) NULL)
2191 flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
2192 if ((flags & HeightValue) == 0)
2193 tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
2194 tile_columns=(uint32) tiff_info->tile_geometry.width;
2195 tile_rows=(uint32) tiff_info->tile_geometry.height;
2196 TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
2197 (void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
2198 (void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
2199 tiff_info->tile_geometry.width=tile_columns;
2200 tiff_info->tile_geometry.height=tile_rows;
2201 tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
2202 tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
2203 tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
2204 tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
2205 if ((tiff_info->scanlines == (unsigned char *) NULL) ||
2206 (tiff_info->pixels == (unsigned char *) NULL))
2208 DestroyTIFFInfo(tiff_info);
2209 return(MagickFalse);
2214 static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
2215 tsample_t sample,Image *image)
2223 register unsigned char
2237 if (TIFFIsTiled(tiff) == 0)
2238 return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
2240 Fill scanlines to tile height.
2242 i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
2243 (void) CopyMagickMemory(tiff_info->scanlines+i,(char *) tiff_info->scanline,
2244 (size_t) TIFFScanlineSize(tiff));
2245 if (((size_t) (row % tiff_info->tile_geometry.height) !=
2246 (tiff_info->tile_geometry.height-1)) &&
2247 (row != (ssize_t) (image->rows-1)))
2250 Write tile to TIFF image.
2253 bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
2254 tiff_info->tile_geometry.width);
2255 number_tiles=(image->columns+tiff_info->tile_geometry.width)/
2256 tiff_info->tile_geometry.width;
2257 for (i=0; i < (ssize_t) number_tiles; i++)
2259 tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
2260 tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
2261 for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
2262 for (k=0; k < (ssize_t) tile_width; k++)
2264 if (bytes_per_pixel == 0)
2266 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2267 tiff_info->tile_geometry.width+k)/8);
2268 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
2272 p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
2273 tiff_info->tile_geometry.width+k)*bytes_per_pixel);
2274 q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
2275 for (l=0; l < bytes_per_pixel; l++)
2278 if ((i*tiff_info->tile_geometry.width) != image->columns)
2279 status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
2280 tiff_info->tile_geometry.width),(uint32) ((row/
2281 tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
2289 static void TIFFSetProfiles(TIFF *tiff,Image *image)
2297 if (image->profiles == (void *) NULL)
2299 ResetImageProfileIterator(image);
2300 for (name=GetNextImageProfile(image); name != (const char *) NULL; )
2302 profile=GetImageProfile(image,name);
2303 #if defined(TIFFTAG_XMLPACKET)
2304 if (LocaleCompare(name,"xmp") == 0)
2305 (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
2306 profile),GetStringInfoDatum(profile));
2308 #if defined(TIFFTAG_ICCPROFILE)
2309 if (LocaleCompare(name,"icc") == 0)
2310 (void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
2311 profile),GetStringInfoDatum(profile));
2313 if (LocaleCompare(name,"iptc") == 0)
2321 iptc_profile=CloneStringInfo(profile);
2322 length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
2324 SetStringInfoLength(iptc_profile,length);
2325 if (TIFFIsByteSwapped(tiff))
2326 TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
2327 (unsigned long) (length/4));
2328 (void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
2329 GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
2330 iptc_profile=DestroyStringInfo(iptc_profile);
2332 #if defined(TIFFTAG_PHOTOSHOP)
2333 if (LocaleCompare(name,"8bim") == 0)
2334 (void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
2335 GetStringInfoLength(profile),GetStringInfoDatum(profile));
2337 if (LocaleCompare(name,"tiff:37724") == 0)
2338 (void) TIFFSetField(tiff,37724,(uint32)GetStringInfoLength(profile),
2339 GetStringInfoDatum(profile));
2340 name=GetNextImageProfile(image);
2344 static void TIFFSetProperties(TIFF *tiff,Image *image)
2349 (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
2350 value=GetImageProperty(image,"tiff:hostcomputer");
2351 if (value != (const char *) NULL)
2352 (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
2353 value=GetImageProperty(image,"tiff:artist");
2354 if (value != (const char *) NULL)
2355 (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
2356 value=GetImageProperty(image,"tiff:timestamp");
2357 if (value != (const char *) NULL)
2358 (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
2359 value=GetImageProperty(image,"tiff:make");
2360 if (value != (const char *) NULL)
2361 (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
2362 value=GetImageProperty(image,"tiff:model");
2363 if (value != (const char *) NULL)
2364 (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
2365 value=GetImageProperty(image,"tiff:software");
2366 if (value != (const char *) NULL)
2367 (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
2368 value=GetImageProperty(image,"tiff:copyright");
2369 if (value != (const char *) NULL)
2370 (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
2371 value=GetImageProperty(image,"kodak-33423");
2372 if (value != (const char *) NULL)
2373 (void) TIFFSetField(tiff,33423,value);
2374 value=GetImageProperty(image,"kodak-36867");
2375 if (value != (const char *) NULL)
2376 (void) TIFFSetField(tiff,36867,value);
2377 value=GetImageProperty(image,"label");
2378 if (value != (const char *) NULL)
2379 (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
2380 value=GetImageProperty(image,"comment");
2381 if (value != (const char *) NULL)
2382 (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
2385 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
2387 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
2398 Write EXIF properties.
2401 (void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
2402 for (i=0; exif_info[i].tag != 0; i++)
2404 value=GetImageProperty(image,exif_info[i].property);
2405 if (value == (const char *) NULL)
2407 switch (exif_info[i].type)
2411 (void) TIFFSetField(tiff,exif_info[i].tag,value);
2419 shorty=(uint16) StringToLong(value);
2420 (void) TIFFSetField(tiff,exif_info[i].tag,shorty);
2428 ssize_ty=(uint16) StringToLong(value);
2429 (void) TIFFSetField(tiff,exif_info[i].tag,ssize_ty);
2433 case TIFF_SRATIONAL:
2438 rational=InterpretLocaleValue(value,(char **) NULL);
2439 (void) TIFFSetField(tiff,exif_info[i].tag,rational);
2446 /* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
2453 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
2454 Image *image,ExceptionInfo *exception)
2456 #if !defined(TIFFDefaultStripSize)
2457 #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff))
2518 assert(image_info != (const ImageInfo *) NULL);
2519 assert(image_info->signature == MagickSignature);
2520 assert(image != (Image *) NULL);
2521 assert(image->signature == MagickSignature);
2522 if (image->debug != MagickFalse)
2523 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2524 assert(exception != (ExceptionInfo *) NULL);
2525 assert(exception->signature == MagickSignature);
2526 assert(exception != (ExceptionInfo *) NULL);
2527 assert(exception->signature == MagickSignature);
2528 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
2529 if (status == MagickFalse)
2531 (void) MagickSetThreadValue(tiff_exception,exception);
2532 error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
2533 warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
2534 endian_type=UndefinedEndian;
2535 option=GetImageOption(image_info,"tiff:endian");
2536 if (option != (const char *) NULL)
2538 if (LocaleNCompare(option,"msb",3) == 0)
2539 endian_type=MSBEndian;
2540 if (LocaleNCompare(option,"lsb",3) == 0)
2541 endian_type=LSBEndian;;
2543 switch (endian_type)
2545 case LSBEndian: mode="wl"; break;
2546 case MSBEndian: mode="wb"; break;
2547 default: mode="w"; break;
2549 #if defined(TIFF_VERSION_BIG)
2550 if (LocaleCompare(image_info->magick,"TIFF64") == 0)
2551 switch (endian_type)
2553 case LSBEndian: mode="wl8"; break;
2554 case MSBEndian: mode="wb8"; break;
2555 default: mode="w8"; break;
2558 tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
2559 TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
2561 if (tiff == (TIFF *) NULL)
2563 (void) TIFFSetWarningHandler(warning_handler);
2564 (void) TIFFSetErrorHandler(error_handler);
2565 return(MagickFalse);
2568 debug=IsEventLogging();
2573 Initialize TIFF fields.
2575 if ((image_info->type != UndefinedType) &&
2576 (image_info->type != OptimizeType))
2577 (void) SetImageType(image,image_info->type,exception);
2578 quantum_info=AcquireQuantumInfo(image_info,image);
2579 if (quantum_info == (QuantumInfo *) NULL)
2580 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2581 if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
2582 (quantum_info->format == UndefinedQuantumFormat) &&
2583 (IsHighDynamicRangeImage(image,exception) != MagickFalse))
2585 status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
2586 if (status == MagickFalse)
2587 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
2589 if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
2590 (GetPreviousImageInList(image) != (Image *) NULL))
2591 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
2592 if ((image->columns != (uint32) image->columns) ||
2593 (image->rows != (uint32) image->rows))
2594 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
2595 (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
2596 (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
2597 compression=image->compression;
2598 if (image_info->compression != UndefinedCompression)
2599 compression=image_info->compression;
2600 switch (compression)
2602 case FaxCompression:
2604 compress_tag=COMPRESSION_CCITTFAX3;
2605 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2608 case Group4Compression:
2610 compress_tag=COMPRESSION_CCITTFAX4;
2611 SetQuantumMinIsWhite(quantum_info,MagickTrue);
2614 #if defined(COMPRESSION_JBIG)
2615 case JBIG1Compression:
2617 compress_tag=COMPRESSION_JBIG;
2621 case JPEGCompression:
2623 compress_tag=COMPRESSION_JPEG;
2626 #if defined(COMPRESSION_LZMA)
2627 case LZMACompression:
2629 compress_tag=COMPRESSION_LZMA;
2633 case LZWCompression:
2635 compress_tag=COMPRESSION_LZW;
2638 case RLECompression:
2640 compress_tag=COMPRESSION_PACKBITS;
2643 case ZipCompression:
2645 compress_tag=COMPRESSION_ADOBE_DEFLATE;
2651 compress_tag=COMPRESSION_NONE;
2655 #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
2656 if ((compress_tag != COMPRESSION_NONE) &&
2657 (TIFFIsCODECConfigured(compress_tag) == 0))
2659 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2660 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2661 MagickCompressOptions,(ssize_t) compression));
2662 compress_tag=COMPRESSION_NONE;
2663 compression=NoCompression;
2666 switch (compress_tag)
2668 #if defined(CCITT_SUPPORT)
2669 case COMPRESSION_CCITTFAX3:
2670 case COMPRESSION_CCITTFAX4:
2672 #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
2673 case COMPRESSION_JPEG:
2675 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2676 case COMPRESSION_LZMA:
2678 #if defined(LZW_SUPPORT)
2679 case COMPRESSION_LZW:
2681 #if defined(PACKBITS_SUPPORT)
2682 case COMPRESSION_PACKBITS:
2684 #if defined(ZIP_SUPPORT)
2685 case COMPRESSION_ADOBE_DEFLATE:
2687 case COMPRESSION_NONE:
2691 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
2692 "CompressionNotSupported","`%s'",CommandOptionToMnemonic(
2693 MagickCompressOptions,(ssize_t) compression));
2694 compress_tag=COMPRESSION_NONE;
2695 compression=NoCompression;
2700 switch (compression)
2702 case FaxCompression:
2703 case Group4Compression:
2705 (void) SetImageType(image,BilevelType,exception);
2708 case JPEGCompression:
2710 (void) SetImageStorageClass(image,DirectClass,exception);
2711 (void) SetImageDepth(image,8);
2717 if (image->colorspace == CMYKColorspace)
2719 photometric=PHOTOMETRIC_SEPARATED;
2720 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
2721 (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
2726 Full color TIFF raster.
2728 if (image->colorspace == LabColorspace)
2729 photometric=PHOTOMETRIC_CIELAB;
2731 if (image->colorspace == YCbCrColorspace)
2733 photometric=PHOTOMETRIC_YCBCR;
2734 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
2735 (void) SetImageStorageClass(image,DirectClass,exception);
2736 (void) SetImageDepth(image,8);
2740 if (IsRGBColorspace(image->colorspace) == MagickFalse)
2741 (void) TransformImageColorspace(image,RGBColorspace);
2742 photometric=PHOTOMETRIC_RGB;
2744 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
2745 if ((image_info->type != TrueColorType) &&
2746 (image_info->type != TrueColorMatteType))
2748 if ((image_info->type != PaletteType) &&
2749 (IsImageGray(image,exception) != MagickFalse))
2751 photometric=(uint16) (quantum_info->min_is_white !=
2752 MagickFalse ? PHOTOMETRIC_MINISWHITE :
2753 PHOTOMETRIC_MINISBLACK);
2754 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2755 if ((image_info->depth == 0) && (image->matte == MagickFalse) &&
2756 (IsImageMonochrome(image,exception) != MagickFalse))
2758 status=SetQuantumDepth(image,quantum_info,1);
2759 if (status == MagickFalse)
2760 ThrowWriterException(ResourceLimitError,
2761 "MemoryAllocationFailed");
2765 if (image->storage_class == PseudoClass)
2771 Colormapped TIFF raster.
2773 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
2774 photometric=PHOTOMETRIC_PALETTE;
2776 while ((GetQuantumRange(depth)+1) < image->colors)
2778 status=SetQuantumDepth(image,quantum_info,depth);
2779 if (status == MagickFalse)
2780 ThrowWriterException(ResourceLimitError,
2781 "MemoryAllocationFailed");
2785 switch (image->endian)
2789 endian=FILLORDER_LSB2MSB;
2794 endian=FILLORDER_MSB2LSB;
2797 case UndefinedEndian:
2800 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
2805 image->endian=MSBEndian;
2806 if ((int) (*(char *) &lsb_first) != 0)
2807 image->endian=LSBEndian;
2808 if ((compress_tag == COMPRESSION_CCITTFAX3) &&
2809 (photometric != PHOTOMETRIC_MINISWHITE))
2811 compress_tag=COMPRESSION_NONE;
2812 endian=FILLORDER_MSB2LSB;
2815 if ((compress_tag == COMPRESSION_CCITTFAX4) &&
2816 (photometric != PHOTOMETRIC_MINISWHITE))
2818 compress_tag=COMPRESSION_NONE;
2819 endian=FILLORDER_MSB2LSB;
2821 option=GetImageProperty(image,"tiff:fill-order");
2822 if (option != (const char *) NULL)
2824 if (LocaleNCompare(option,"msb",3) == 0)
2825 endian=FILLORDER_MSB2LSB;
2826 if (LocaleNCompare(option,"lsb",3) == 0)
2827 endian=FILLORDER_LSB2MSB;
2829 (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
2830 (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
2831 (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
2832 if (image->matte != MagickFalse)
2840 TIFF has a matte channel.
2843 sample_info[0]=EXTRASAMPLE_UNASSALPHA;
2844 option=GetImageProperty(image,"tiff:alpha");
2845 if ((option != (const char *) NULL) &&
2846 (LocaleCompare(option,"associated") == 0))
2847 sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
2848 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
2849 &samples_per_pixel);
2850 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
2851 (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
2853 if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
2854 SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
2856 (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
2857 switch (quantum_info->format)
2859 case FloatingPointQuantumFormat:
2861 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
2862 (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
2863 (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
2866 case SignedQuantumFormat:
2868 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
2871 case UnsignedQuantumFormat:
2873 (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
2879 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
2880 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
2881 if (photometric == PHOTOMETRIC_RGB)
2882 if ((image_info->interlace == PlaneInterlace) ||
2883 (image_info->interlace == PartitionInterlace))
2884 (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
2886 if (TIFFScanlineSize(tiff) != 0)
2887 rows_per_strip=(uint32) MagickMax((size_t) TIFFDefaultStripSize(tiff,0),
2889 option=GetImageOption(image_info,"tiff:rows-per-strip");
2890 if (option != (const char *) NULL)
2891 rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
2892 switch (compress_tag)
2894 case COMPRESSION_JPEG:
2896 #if defined(JPEG_SUPPORT)
2906 rows_per_strip+=(16-(rows_per_strip % 16));
2907 if (image->quality != 0)
2908 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image->quality);
2909 if (image_info->quality != UndefinedCompressionQuality)
2910 (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
2911 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
2912 if (IsRGBColorspace(image->colorspace) == MagickTrue)
2917 (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
2918 sampling_factor=(const char *) NULL;
2919 value=GetImageProperty(image,"jpeg:sampling-factor");
2920 if (value != (char *) NULL)
2922 sampling_factor=value;
2923 if (image->debug != MagickFalse)
2924 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
2925 " Input sampling-factors=%s",sampling_factor);
2927 if (image_info->sampling_factor != (char *) NULL)
2928 sampling_factor=image_info->sampling_factor;
2929 if (sampling_factor != (const char *) NULL)
2931 flags=ParseGeometry(sampling_factor,&geometry_info);
2932 if ((flags & SigmaValue) == 0)
2933 geometry_info.sigma=geometry_info.rho;
2934 if (image->colorspace == YCbCrColorspace)
2935 (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
2936 geometry_info.rho,(uint16) geometry_info.sigma);
2939 if (bits_per_sample == 12)
2940 (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
2944 case COMPRESSION_ADOBE_DEFLATE:
2946 rows_per_strip=(uint32) image->rows;
2947 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
2949 if (((photometric == PHOTOMETRIC_RGB) ||
2950 (photometric == PHOTOMETRIC_MINISBLACK)) &&
2951 ((bits_per_sample == 8) || (bits_per_sample == 16)))
2952 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2953 (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
2954 image_info->quality == UndefinedCompressionQuality ? 7 :
2955 MagickMin((ssize_t) image_info->quality/10,9)));
2958 case COMPRESSION_CCITTFAX3:
2963 rows_per_strip=(uint32) image->rows;
2964 (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
2967 case COMPRESSION_CCITTFAX4:
2969 rows_per_strip=(uint32) image->rows;
2972 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
2973 case COMPRESSION_LZMA:
2975 if (((photometric == PHOTOMETRIC_RGB) ||
2976 (photometric == PHOTOMETRIC_MINISBLACK)) &&
2977 ((bits_per_sample == 8) || (bits_per_sample == 16)))
2978 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2979 (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
2980 image_info->quality == UndefinedCompressionQuality ? 7 :
2981 MagickMin((ssize_t) image_info->quality/10,9)));
2985 case COMPRESSION_LZW:
2987 (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
2989 if (((photometric == PHOTOMETRIC_RGB) ||
2990 (photometric == PHOTOMETRIC_MINISBLACK)) &&
2991 ((bits_per_sample == 8) || (bits_per_sample == 16)))
2992 (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL);
2998 option=GetImageOption(image_info,"tiff:tile-geometry");
2999 if (option == (const char *) NULL)
3000 (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
3001 if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
3007 Set image resolution.
3010 if (image->units == PixelsPerInchResolution)
3012 if (image->units == PixelsPerCentimeterResolution)
3013 units=RESUNIT_CENTIMETER;
3014 (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
3015 (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
3016 (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
3017 if ((image->page.x != 0) || (image->page.y != 0))
3022 (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
3023 image->x_resolution);
3024 (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
3025 image->y_resolution);
3028 if (image->chromaticity.white_point.x != 0.0)
3034 Set image chromaticity.
3036 chromaticity[0]=(float) image->chromaticity.red_primary.x;
3037 chromaticity[1]=(float) image->chromaticity.red_primary.y;
3038 chromaticity[2]=(float) image->chromaticity.green_primary.x;
3039 chromaticity[3]=(float) image->chromaticity.green_primary.y;
3040 chromaticity[4]=(float) image->chromaticity.blue_primary.x;
3041 chromaticity[5]=(float) image->chromaticity.blue_primary.y;
3042 (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
3043 chromaticity[0]=(float) image->chromaticity.white_point.x;
3044 chromaticity[1]=(float) image->chromaticity.white_point.y;
3045 (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
3047 if ((image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1))
3049 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3050 if (image->scene != 0)
3051 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
3052 GetImageListLength(image));
3054 if (image->orientation != UndefinedOrientation)
3055 (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
3056 (void) TIFFSetProfiles(tiff,image);
3062 page=(uint16) scene;
3063 pages=(uint16) GetImageListLength(image);
3064 if ((image_info->adjoin != MagickFalse) && (pages > 1))
3065 (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
3066 (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
3068 (void) TIFFSetProperties(tiff,image);
3070 (void) TIFFSetEXIFProperties(tiff,image);
3072 Write image scanlines.
3074 if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
3075 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3076 pixels=GetQuantumPixels(quantum_info);
3077 tiff_info.scanline=GetQuantumPixels(quantum_info);
3078 switch (photometric)
3080 case PHOTOMETRIC_CIELAB:
3081 case PHOTOMETRIC_YCBCR:
3082 case PHOTOMETRIC_RGB:
3087 switch (image_info->interlace)
3092 quantum_type=RGBQuantum;
3093 if (image->matte != MagickFalse)
3094 quantum_type=RGBAQuantum;
3095 for (y=0; y < (ssize_t) image->rows; y++)
3097 register const Quantum
3100 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3101 if (p == (const Quantum *) NULL)
3103 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3104 quantum_type,pixels,exception);
3106 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3108 if (image->previous == (Image *) NULL)
3110 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
3112 if (status == MagickFalse)
3118 case PlaneInterlace:
3119 case PartitionInterlace:
3122 Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
3124 for (y=0; y < (ssize_t) image->rows; y++)
3126 register const Quantum
3129 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3130 if (p == (const Quantum *) NULL)
3132 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3133 RedQuantum,pixels,exception);
3134 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3137 if (image->previous == (Image *) NULL)
3139 status=SetImageProgress(image,SaveImageTag,100,400);
3140 if (status == MagickFalse)
3143 for (y=0; y < (ssize_t) image->rows; y++)
3145 register const Quantum
3148 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3149 if (p == (const Quantum *) NULL)
3151 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3152 GreenQuantum,pixels,exception);
3153 if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
3156 if (image->previous == (Image *) NULL)
3158 status=SetImageProgress(image,SaveImageTag,200,400);
3159 if (status == MagickFalse)
3162 for (y=0; y < (ssize_t) image->rows; y++)
3164 register const Quantum
3167 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3168 if (p == (const Quantum *) NULL)
3170 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3171 BlueQuantum,pixels,exception);
3172 if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
3175 if (image->previous == (Image *) NULL)
3177 status=SetImageProgress(image,SaveImageTag,300,400);
3178 if (status == MagickFalse)
3181 if (image->matte != MagickFalse)
3182 for (y=0; y < (ssize_t) image->rows; y++)
3184 register const Quantum
3187 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3188 if (p == (const Quantum *) NULL)
3190 length=ExportQuantumPixels(image,(CacheView *) NULL,
3191 quantum_info,AlphaQuantum,pixels,exception);
3192 if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
3195 if (image->previous == (Image *) NULL)
3197 status=SetImageProgress(image,SaveImageTag,400,400);
3198 if (status == MagickFalse)
3206 case PHOTOMETRIC_SEPARATED:
3211 quantum_type=CMYKQuantum;
3212 if (image->matte != MagickFalse)
3213 quantum_type=CMYKAQuantum;
3214 if (image->colorspace != CMYKColorspace)
3215 (void) TransformImageColorspace(image,CMYKColorspace);
3216 for (y=0; y < (ssize_t) image->rows; y++)
3218 register const Quantum
3221 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3222 if (p == (const Quantum *) NULL)
3224 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3225 quantum_type,pixels,exception);
3226 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3228 if (image->previous == (Image *) NULL)
3230 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3232 if (status == MagickFalse)
3238 case PHOTOMETRIC_PALETTE:
3246 Colormapped TIFF image.
3248 red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
3249 green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
3250 blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
3251 if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
3252 (blue == (uint16 *) NULL))
3253 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
3255 Initialize TIFF colormap.
3257 (void) ResetMagickMemory(red,0,65536*sizeof(*red));
3258 (void) ResetMagickMemory(green,0,65536*sizeof(*green));
3259 (void) ResetMagickMemory(blue,0,65536*sizeof(*blue));
3260 for (i=0; i < (ssize_t) image->colors; i++)
3262 red[i]=ScaleQuantumToShort(image->colormap[i].red);
3263 green[i]=ScaleQuantumToShort(image->colormap[i].green);
3264 blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
3266 (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
3267 red=(uint16 *) RelinquishMagickMemory(red);
3268 green=(uint16 *) RelinquishMagickMemory(green);
3269 blue=(uint16 *) RelinquishMagickMemory(blue);
3274 Convert PseudoClass packets to contiguous grayscale scanlines.
3276 quantum_type=IndexQuantum;
3277 if (image->matte != MagickFalse)
3279 if (photometric != PHOTOMETRIC_PALETTE)
3280 quantum_type=GrayAlphaQuantum;
3282 quantum_type=IndexAlphaQuantum;
3285 if (photometric != PHOTOMETRIC_PALETTE)
3286 quantum_type=GrayQuantum;
3287 for (y=0; y < (ssize_t) image->rows; y++)
3289 register const Quantum
3292 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
3293 if (p == (const Quantum *) NULL)
3295 length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
3296 quantum_type,pixels,exception);
3297 if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
3299 if (image->previous == (Image *) NULL)
3301 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
3303 if (status == MagickFalse)
3310 quantum_info=DestroyQuantumInfo(quantum_info);
3311 DestroyTIFFInfo(&tiff_info);
3312 if (0 && (image_info->verbose == MagickTrue))
3313 TIFFPrintDirectory(tiff,stdout,MagickFalse);
3314 (void) TIFFWriteDirectory(tiff);
3315 image->endian=MSBEndian;
3316 if (endian == FILLORDER_LSB2MSB)
3317 image->endian=LSBEndian;
3318 image=SyncNextImageInList(image);
3319 if (image == (Image *) NULL)
3321 status=SetImageProgress(image,SaveImagesTag,scene++,
3322 GetImageListLength(image));
3323 if (status == MagickFalse)
3325 } while (image_info->adjoin != MagickFalse);
3326 (void) TIFFSetWarningHandler(warning_handler);
3327 (void) TIFFSetErrorHandler(error_handler);