]> granicus.if.org Git - imagemagick/blobdiff - coders/tiff.c
Removed png_write_chunk_from_profile()
[imagemagick] / coders / tiff.c
index 72398b1aa97d2254bb7cf316b29558b11aa75a11..5de499038afa1a8ff6a9766616025d4e4107b9a0 100644 (file)
 %                                 July 1992                                   %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization      %
 %  dedicated to making software imaging solutions freely available.           %
 %                                                                             %
 %  You may not use this file except in compliance with the License.  You may  %
 %  obtain a copy of the License at                                            %
 %                                                                             %
-%    http://www.imagemagick.org/script/license.php                            %
+%    https://www.imagemagick.org/script/license.php                           %
 %                                                                             %
 %  Unless required by applicable law or agreed to in writing, software        %
 %  distributed under the License is distributed on an "AS IS" BASIS,          %
 %
 */
 \f
+#ifdef __VMS
+#define JPEG_SUPPORT 1
+#endif
+
 /*
   Include declarations.
 */
@@ -61,6 +65,7 @@
 #include "MagickCore/log.h"
 #include "MagickCore/magick.h"
 #include "MagickCore/memory_.h"
+#include "MagickCore/memory-private.h"
 #include "MagickCore/module.h"
 #include "MagickCore/monitor.h"
 #include "MagickCore/monitor-private.h"
 # if !defined(TIFFTAG_OPIIMAGEID)
 #  define TIFFTAG_OPIIMAGEID  32781
 # endif
-\f
+#include "psd-private.h"
+
 /*
   Typedef declarations.
 */
@@ -198,6 +204,10 @@ static MagickThreadKey
 static SemaphoreInfo
   *tiff_semaphore = (SemaphoreInfo *) NULL;
 
+static TIFFErrorHandler
+  error_handler,
+  warning_handler;
+
 static volatile MagickBooleanType
   instantiate_key = MagickFalse;
 \f
@@ -303,7 +313,7 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
   ExceptionInfo *exception)
 {
   char
-    filename[MaxTextExtent];
+    filename[MagickPathExtent];
 
   FILE
     *file;
@@ -332,12 +342,12 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
     Open image file.
   */
   assert(image_info != (const ImageInfo *) NULL);
-  assert(image_info->signature == MagickSignature);
+  assert(image_info->signature == MagickCoreSignature);
   if (image_info->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
       image_info->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
+  assert(exception->signature == MagickCoreSignature);
   image=AcquireImage(image_info,exception);
   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
   if (status == MagickFalse)
@@ -355,6 +365,8 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
   if ((unique_file == -1) || (file == (FILE *) NULL))
     ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
   length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
+  if (length != 10)
+    ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
   length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
   length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
   length=WriteLSBLong(file,image->columns);
@@ -381,10 +393,17 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
   length=fwrite("\000\000\000\000",1,4,file);
   length=WriteLSBLong(file,(long) image->resolution.x);
   length=WriteLSBLong(file,1);
+  status=MagickTrue;
   for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
-    (void) fputc(c,file);
+    if (fputc(c,file) != c)
+      status=MagickFalse;
   offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
   length=WriteLSBLong(file,(unsigned int) length);
+  if (ferror(file) != 0)
+    {
+      (void) fclose(file);
+      ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
+    }
   (void) fclose(file);
   (void) CloseBlob(image);
   image=DestroyImage(image);
@@ -392,18 +411,20 @@ static Image *ReadGROUP4Image(const ImageInfo *image_info,
     Read TIFF image.
   */
   read_info=CloneImageInfo((ImageInfo *) NULL);
-  (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
+  (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename);
   image=ReadTIFFImage(read_info,exception);
   read_info=DestroyImageInfo(read_info);
   if (image != (Image *) NULL)
     {
       (void) CopyMagickString(image->filename,image_info->filename,
-        MaxTextExtent);
+        MagickPathExtent);
       (void) CopyMagickString(image->magick_filename,image_info->filename,
-        MaxTextExtent);
-      (void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
+        MagickPathExtent);
+      (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent);
     }
   (void) RelinquishUniqueFileResource(filename);
+  if (status == MagickFalse)
+    image=DestroyImage(image);
   return(image);
 }
 #endif
@@ -463,7 +484,7 @@ static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -499,22 +520,8 @@ static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
   return(status);
 }
 
-static inline size_t MagickMax(const size_t x,const size_t y)
-{
-  if (x > y)
-    return(x);
-  return(y);
-}
-
-static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
-{
-  if (x < y)
-    return(x);
-  return(y);
-}
-
 static MagickBooleanType ReadProfile(Image *image,const char *name,
-  unsigned char *datum,ssize_t length,ExceptionInfo *exception)
+  const unsigned char *datum,ssize_t length,ExceptionInfo *exception)
 {
   MagickBooleanType
     status;
@@ -524,11 +531,6 @@ static MagickBooleanType ReadProfile(Image *image,const char *name,
 
   if (length < 4)
     return(MagickFalse);
-  if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"xmp") != 0))
-    {
-      if (strstr((char *) datum,"8BIM") == (char *) NULL)
-        return(MagickFalse);
-    }
   profile=BlobToStringInfo(datum,(size_t) length);
   if (profile == (StringInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
@@ -554,18 +556,18 @@ static int TIFFCloseBlob(thandle_t image)
 static void TIFFErrors(const char *module,const char *format,va_list error)
 {
   char
-    message[MaxTextExtent];
+    message[MagickPathExtent];
 
   ExceptionInfo
     *exception;
 
 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
-  (void) vsnprintf(message,MaxTextExtent,format,error);
+  (void) vsnprintf(message,MagickPathExtent,format,error);
 #else
   (void) vsprintf(message,format,error);
 #endif
-  (void) ConcatenateMagickString(message,".",MaxTextExtent);
-  exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
+  (void) ConcatenateMagickString(message,".",MagickPathExtent);
+  exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
   if (exception != (ExceptionInfo *) NULL)
     (void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
       "`%s'",module);
@@ -609,64 +611,111 @@ static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
       (profile != (unsigned char *) NULL))
     (void) ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
 #endif
+  if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
+      (profile != (unsigned char *) NULL))
+    (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,
+      exception);
   if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
       (profile != (unsigned char *) NULL))
     (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
-  if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
-      (profile != (unsigned char *) NULL))
-    (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,exception);
 }
 
 static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
 {
   char
-    message[MaxTextExtent],
+    message[MagickPathExtent],
     *text;
 
   uint32
-    count;
+    count,
+    length,
+    type;
+
+  unsigned long
+    *tietz;
 
-  if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:artist",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:copyright",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:timestamp",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:document",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:hostcomputer",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"comment",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:make",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:model",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) &&
+      (text != (char *) NULL))
     {
-      if (count >= MaxTextExtent)
-        count=MaxTextExtent-1;
+      if (count >= MagickPathExtent)
+        count=MagickPathExtent-1;
       (void) CopyMagickString(message,text,count+1);
       (void) SetImageProperty(image,"tiff:image-id",message,exception);
     }
-  if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"label",text,exception);
-  if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1)
+  if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) &&
+      (text != (char *) NULL))
     (void) SetImageProperty(image,"tiff:software",text,exception);
-  if (TIFFGetField(tiff,33423,&count,&text) == 1)
+  if ((TIFFGetField(tiff,33423,&count,&text) == 1) &&
+      (text != (char *) NULL))
     {
-      if (count >= MaxTextExtent)
-        count=MaxTextExtent-1;
+      if (count >= MagickPathExtent)
+        count=MagickPathExtent-1;
       (void) CopyMagickString(message,text,count+1);
       (void) SetImageProperty(image,"tiff:kodak-33423",message,exception);
     }
-  if (TIFFGetField(tiff,36867,&count,&text) == 1)
+  if ((TIFFGetField(tiff,36867,&count,&text) == 1) &&
+      (text != (char *) NULL))
     {
-      if (count >= MaxTextExtent)
-        count=MaxTextExtent-1;
+      if (count >= MagickPathExtent)
+        count=MagickPathExtent-1;
       (void) CopyMagickString(message,text,count+1);
       (void) SetImageProperty(image,"tiff:kodak-36867",message,exception);
     }
+  if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
+    switch (type)
+    {
+      case 0x01:
+      {
+        (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE",
+          exception);
+        break;
+      }
+      case 0x02:
+      {
+        (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception);
+        break;
+      }
+      case 0x04:
+      {
+        (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception);
+        break;
+      }
+      default:
+        break;
+    }
+  if ((TIFFGetField(tiff,37706,&length,&tietz) == 1) &&
+      (tietz != (unsigned long *) NULL))
+    {
+      (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]);
+      (void) SetImageProperty(image,"tiff:tietz_offset",message,exception);
+    }
 }
 
 static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
@@ -674,7 +723,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 {
 #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
   char
-    value[MaxTextExtent];
+    value[MagickPathExtent];
 
   register ssize_t
     i;
@@ -701,7 +750,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
   directory=TIFFCurrentDirectory(tiff);
   if (TIFFReadEXIFDirectory(tiff,offset) != 1)
     {
-      directory=TIFFCurrentDirectory(tiff);
+      TIFFSetDirectory(tiff,directory);
       return;
     }
   sans=NULL;
@@ -718,7 +767,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
         ascii=(char *) NULL;
         if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,&sans,&sans) == 1) &&
             (ascii != (char *) NULL) && (*ascii != '\0'))
-          (void) CopyMagickString(value,ascii,MaxTextExtent);
+          (void) CopyMagickString(value,ascii,MagickPathExtent);
         break;
       }
       case TIFF_SHORT:
@@ -730,23 +779,23 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 
             shorty=0;
             if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1)
-              (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
+              (void) FormatLocaleString(value,MagickPathExtent,"%d",shorty);
           }
         else
-          { 
+          {
             int
               tiff_status;
-            
+
             uint16
               *shorty;
-            
+
             uint16
               shorty_num;
-            
+
             tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
-              &sans,&sans); 
+              &sans,&sans);
             if (tiff_status == 1)
-              (void) FormatLocaleString(value,MaxTextExtent,"%d",
+              (void) FormatLocaleString(value,MagickPathExtent,"%d",
                 shorty_num != 0 ? shorty[0] : 0);
           }
         break;
@@ -758,7 +807,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 
         longy=0;
         if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1)
-          (void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
+          (void) FormatLocaleString(value,MagickPathExtent,"%d",longy);
         break;
       }
 #if defined(TIFF_VERSION_BIG)
@@ -769,7 +818,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 
         long8y=0;
         if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1)
-          (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
+          (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
             ((MagickOffsetType) long8y));
         break;
       }
@@ -783,7 +832,8 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 
         floaty=0.0;
         if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) == 1)
-          (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
+          (void) FormatLocaleString(value,MagickPathExtent,"%g",(double)
+            floaty);
         break;
       }
       case TIFF_DOUBLE:
@@ -793,7 +843,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
 
         doubley=0.0;
         if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1)
-          (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
+          (void) FormatLocaleString(value,MagickPathExtent,"%g",doubley);
         break;
       }
       default:
@@ -855,18 +905,18 @@ static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
 static void TIFFWarnings(const char *module,const char *format,va_list warning)
 {
   char
-    message[MaxTextExtent];
+    message[MagickPathExtent];
 
   ExceptionInfo
     *exception;
 
 #if defined(MAGICKCORE_HAVE_VSNPRINTF)
-  (void) vsnprintf(message,MaxTextExtent,format,warning);
+  (void) vsnprintf(message,MagickPathExtent,format,warning);
 #else
   (void) vsprintf(message,format,warning);
 #endif
-  (void) ConcatenateMagickString(message,".",MaxTextExtent);
-  exception=(ExceptionInfo *) MagickGetThreadValue(tiff_exception);
+  (void) ConcatenateMagickString(message,".",MagickPathExtent);
+  exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
   if (exception != (ExceptionInfo *) NULL)
     (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
       message,"`%s'",module);
@@ -882,7 +932,7 @@ static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
   return(count);
 }
 
-static TIFFMethodType GetJpegMethod(Image* image,TIFF *tiff,uint16 photometric,
+static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
   uint16 bits_per_sample,uint16 samples_per_pixel)
 {
 #define BUFFER_SIZE 2048
@@ -905,20 +955,20 @@ static TIFFMethodType GetJpegMethod(Image* image,TIFF *tiff,uint16 photometric,
     **value;
 
   unsigned char
-    buffer[BUFFER_SIZE+1];
+    buffer[BUFFER_SIZE+32];
 
   unsigned short
     length;
 
   /* only support 8 bit for now */
-  if (photometric != PHOTOMETRIC_SEPARATED || bits_per_sample != 8 ||
-      samples_per_pixel != 4)
+  if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
+      (samples_per_pixel != 4))
     return(ReadGenericMethod);
   /* Search for Adobe APP14 JPEG Marker */
   if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
     return(ReadRGBAMethod);
   position=TellBlob(image);
-  offset=(MagickOffsetType)value[0];
+  offset=(MagickOffsetType) (value[0]);
   if (SeekBlob(image,offset,SEEK_SET) != offset)
     return(ReadRGBAMethod);
   method=ReadRGBAMethod;
@@ -954,10 +1004,82 @@ static TIFFMethodType GetJpegMethod(Image* image,TIFF *tiff,uint16 photometric,
         i+=(size_t) length;
       }
     }
-  SeekBlob(image,position,SEEK_SET);
+  (void) SeekBlob(image,position,SEEK_SET);
   return(method);
 }
 
+static void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info,
+  ExceptionInfo *exception)
+{
+  const char
+    *option;
+
+  const StringInfo
+    *layer_info;
+
+  Image
+    *layers;
+
+  PSDInfo
+    info;
+
+  register ssize_t
+    i;
+
+  if (GetImageListLength(image) != 1)
+    return;
+  if ((image_info->number_scenes == 1) && (image_info->scene == 0))
+    return;
+  option=GetImageOption(image_info,"tiff:ignore-layers");
+  if (option != (const char * ) NULL)
+    return;
+  layer_info=GetImageProfile(image,"tiff:37724");
+  if (layer_info == (const StringInfo *) NULL)
+    return;
+  for (i=0; i < (ssize_t) layer_info->length-8; i++)
+  {
+    if (LocaleNCompare((const char *) (layer_info->datum+i),
+        image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
+      continue;
+    i+=4;
+    if ((LocaleNCompare((const char *) (layer_info->datum+i),
+         image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
+        (LocaleNCompare((const char *) (layer_info->datum+i),
+         image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
+        (LocaleNCompare((const char *) (layer_info->datum+i),
+         image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
+        (LocaleNCompare((const char *) (layer_info->datum+i),
+         image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
+      break;
+  }
+  i+=4;
+  if (i >= (ssize_t) (layer_info->length-8))
+    return;
+  layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
+  (void) DeleteImageProfile(layers,"tiff:37724");
+  AttachBlob(layers->blob,layer_info->datum,layer_info->length);
+  SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
+  info.version=1;
+  info.columns=layers->columns;
+  info.rows=layers->rows;
+  info.channels=(unsigned short) layers->number_channels;
+  /* Setting the mode to a value that won't change the colorspace */
+  info.mode=10;
+  ReadPSDLayers(layers,image_info,&info,MagickFalse,exception);
+  DeleteImageFromList(&layers);
+  if (layers != (Image *) NULL)
+    {
+      SetImageArtifact(image,"tiff:has-layers","true");
+      AppendImageToList(&image,layers);
+      while (layers != (Image *) NULL)
+      {
+        SetImageArtifact(layers,"tiff:has-layers","true");
+        DetachBlob(layers->blob);
+        layers=GetNextImageInList(layers);
+      }
+    }
+}
+
 #if defined(__cplusplus) || defined(c_plusplus)
 }
 #endif
@@ -982,7 +1104,6 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     tiff_status;
 
   MagickBooleanType
-    debug,
     status;
 
   MagickSizeType
@@ -1006,10 +1127,6 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
   TIFF
     *tiff;
 
-  TIFFErrorHandler
-    error_handler,
-    warning_handler;
-
   TIFFMethodType
     method;
 
@@ -1036,18 +1153,18 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     width;
 
   unsigned char
-    *pixels;
+    *tiff_pixels;
 
   /*
     Open image.
   */
   assert(image_info != (const ImageInfo *) NULL);
-  assert(image_info->signature == MagickSignature);
+  assert(image_info->signature == MagickCoreSignature);
   if (image_info->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
       image_info->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
+  assert(exception->signature == MagickCoreSignature);
   image=AcquireImage(image_info,exception);
   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
   if (status == MagickFalse)
@@ -1055,45 +1172,44 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       image=DestroyImageList(image);
       return((Image *) NULL);
     }
-  (void) MagickSetThreadValue(tiff_exception,exception);
-  error_handler=TIFFSetErrorHandler(TIFFErrors);
-  warning_handler=TIFFSetWarningHandler(TIFFWarnings);
+  (void) SetMagickThreadValue(tiff_exception,exception);
   tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
     TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
     TIFFUnmapBlob);
   if (tiff == (TIFF *) NULL)
     {
-      (void) TIFFSetWarningHandler(warning_handler);
-      (void) TIFFSetErrorHandler(error_handler);
       image=DestroyImageList(image);
       return((Image *) NULL);
     }
-  debug=IsEventLogging();
-  (void) debug;
   if (image_info->number_scenes != 0)
     {
       /*
         Generate blank images for subimage specification (e.g. image.tif[4].
+        We need to check the number of directores because it is possible that
+        the subimage(s) are stored in the photoshop profile.
       */
-      for (i=0; i < (ssize_t) image_info->scene; i++)
-      {
-        status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
-        if (status == MagickFalse)
-          {
-            TIFFClose(tiff);
-            image=DestroyImageList(image);
-            return((Image *) NULL);
-          }
-        AcquireNextImage(image_info,image,exception);
-        if (GetNextImageInList(image) == (Image *) NULL)
+      if (image_info->scene < (size_t) TIFFNumberOfDirectories(tiff))
+        {
+          for (i=0; i < (ssize_t) image_info->scene; i++)
           {
-            TIFFClose(tiff);
-            image=DestroyImageList(image);
-            return((Image *) NULL);
+            status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
+            if (status == MagickFalse)
+              {
+                TIFFClose(tiff);
+                image=DestroyImageList(image);
+                return((Image *) NULL);
+              }
+            AcquireNextImage(image_info,image,exception);
+            if (GetNextImageInList(image) == (Image *) NULL)
+              {
+                TIFFClose(tiff);
+                image=DestroyImageList(image);
+                return((Image *) NULL);
+              }
+            image=SyncNextImageInList(image);
           }
-        image=SyncNextImageInList(image);
       }
-    }
+  }
   do
   {
 DisableMSCWarning(4127)
@@ -1148,11 +1264,23 @@ RestoreMSCWarning
         break;
       }
       case PHOTOMETRIC_LOGL:
+      {
+        (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)",
+          exception);
+        break;
+      }
       case PHOTOMETRIC_LOGLUV:
       {
-        (void) TIFFSetField(tiff,TIFFTAG_SGILOGDATAFMT,SGILOGDATAFMT_FLOAT);
+        (void) SetImageProperty(image,"tiff:photometric","LOGLUV",exception);
+        break;
+      }
+#if defined(PHOTOMETRIC_MASK)
+      case PHOTOMETRIC_MASK:
+      {
+        (void) SetImageProperty(image,"tiff:photometric","MASK",exception);
         break;
       }
+#endif
       case PHOTOMETRIC_SEPARATED:
       {
         (void) SetImageProperty(image,"tiff:photometric","separated",exception);
@@ -1188,9 +1316,6 @@ RestoreMSCWarning
     image->columns=(size_t) width;
     image->rows=(size_t) height;
     image->depth=(size_t) bits_per_sample;
-    status=SetImageExtent(image,image->columns,image->rows,exception);
-    if (status == MagickFalse)
-      return(DestroyImageList(image));
     if (image->debug != MagickFalse)
       (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
         (double) image->depth);
@@ -1216,11 +1341,10 @@ RestoreMSCWarning
       SetImageColorspace(image,CMYKColorspace,exception);
     if (photometric == PHOTOMETRIC_CIELAB)
       SetImageColorspace(image,LabColorspace,exception);
-    if (image_info->ping == MagickFalse)
-      TIFFGetProfiles(tiff,image,exception);
+    TIFFGetProfiles(tiff,image,exception);
     TIFFGetProperties(tiff,image,exception);
     option=GetImageOption(image_info,"tiff:exif-properties");
-    if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
+    if (IsStringFalse(option) == MagickFalse) /* enabled by default */
       TIFFGetEXIFProperties(tiff,image,exception);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
       &samples_per_pixel);
@@ -1284,7 +1408,7 @@ RestoreMSCWarning
 #if defined(JPEG_SUPPORT)
          {
            char
-             sampling_factor[MaxTextExtent];
+             sampling_factor[MagickPathExtent];
 
            int
              tiff_status;
@@ -1293,12 +1417,12 @@ RestoreMSCWarning
              horizontal,
              vertical;
 
-           tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING,
-             &horizontal,&vertical);
+           tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
+             &vertical);
            if (tiff_status == 1)
              {
-               (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
-                 horizontal,vertical);
+               (void) FormatLocaleString(sampling_factor,MagickPathExtent,
+                 "%dx%d",horizontal,vertical);
                (void) SetImageProperty(image,"jpeg:sampling-factor",
                  sampling_factor,exception);
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
@@ -1317,6 +1441,77 @@ RestoreMSCWarning
       case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
       default: image->compression=RLECompression; break;
     }
+    quantum_info=(QuantumInfo *) NULL;
+    if ((photometric == PHOTOMETRIC_PALETTE) &&
+        (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
+      {
+        size_t
+          colors;
+
+        colors=(size_t) GetQuantumRange(bits_per_sample)+1;
+        if (AcquireImageColormap(image,colors,exception) == MagickFalse)
+          {
+            TIFFClose(tiff);
+            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          }
+      }
+    value=(unsigned short) image->scene;
+    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
+      image->scene=value;
+    if (image->storage_class == PseudoClass)
+      {
+        int
+          tiff_status;
+
+        size_t
+          range;
+
+        uint16
+          *blue_colormap,
+          *green_colormap,
+          *red_colormap;
+
+        /*
+          Initialize colormap.
+        */
+        tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
+          &green_colormap,&blue_colormap);
+        if (tiff_status == 1)
+          {
+            if ((red_colormap != (uint16 *) NULL) &&
+                (green_colormap != (uint16 *) NULL) &&
+                (blue_colormap != (uint16 *) NULL))
+              {
+                range=255;  /* might be old style 8-bit colormap */
+                for (i=0; i < (ssize_t) image->colors; i++)
+                  if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
+                      (blue_colormap[i] >= 256))
+                    {
+                      range=65535;
+                      break;
+                    }
+                for (i=0; i < (ssize_t) image->colors; i++)
+                {
+                  image->colormap[i].red=ClampToQuantum(((double)
+                    QuantumRange*red_colormap[i])/range);
+                  image->colormap[i].green=ClampToQuantum(((double)
+                    QuantumRange*green_colormap[i])/range);
+                  image->colormap[i].blue=ClampToQuantum(((double)
+                    QuantumRange*blue_colormap[i])/range);
+                }
+              }
+          }
+      }
+    if (image_info->ping != MagickFalse)
+      {
+        if (image_info->number_scenes != 0)
+          if (image->scene >= (image_info->scene+image_info->number_scenes-1))
+            break;
+        goto next_tiff_frame;
+      }
+    status=SetImageExtent(image,image->columns,image->rows,exception);
+    if (status == MagickFalse)
+      return(DestroyImageList(image));
     /*
       Allocate memory for the image and pixel buffer.
     */
@@ -1334,8 +1529,8 @@ RestoreMSCWarning
       status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
     if (status == MagickFalse)
       {
-        quantum_info=DestroyQuantumInfo(quantum_info);
         TIFFClose(tiff);
+        quantum_info=DestroyQuantumInfo(quantum_info);
         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
       }
     status=MagickTrue;
@@ -1380,44 +1575,25 @@ RestoreMSCWarning
                   exception);
           }
       }
-    if ((photometric == PHOTOMETRIC_PALETTE) &&
-        (pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
-      {
-        size_t
-          colors;
-
-        colors=(size_t) GetQuantumRange(bits_per_sample)+1;
-        if (AcquireImageColormap(image,colors,exception) == MagickFalse)
-          {
-            TIFFClose(tiff);
-            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
-          }
-      }
-    value=(unsigned short) image->scene;
-    if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
-      image->scene=value;
-    if (image_info->ping != MagickFalse)
-      {
-        if (image_info->number_scenes != 0)
-          if (image->scene >= (image_info->scene+image_info->number_scenes-1))
-            break;
-        goto next_tiff_frame;
-      }
     method=ReadGenericMethod;
     if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
       {
         char
-          value[MaxTextExtent];
+          value[MagickPathExtent];
 
         method=ReadStripMethod;
-        (void) FormatLocaleString(value,MaxTextExtent,"%u",
+        (void) FormatLocaleString(value,MagickPathExtent,"%u",
           (unsigned int) rows_per_strip);
         (void) SetImageProperty(image,"tiff:rows-per-strip",value,exception);
       }
-    if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG))
-      method=ReadRGBAMethod;
-    if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE))
-      method=ReadCMYKAMethod;
+    if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
+      if ((image->alpha_trait == UndefinedPixelTrait) ||
+          (samples_per_pixel >= 4))
+        method=ReadRGBAMethod;
+    if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
+      if ((image->alpha_trait == UndefinedPixelTrait) ||
+          (samples_per_pixel >= 5))
+        method=ReadCMYKAMethod;
     if ((photometric != PHOTOMETRIC_RGB) &&
         (photometric != PHOTOMETRIC_CIELAB) &&
         (photometric != PHOTOMETRIC_SEPARATED))
@@ -1431,17 +1607,22 @@ RestoreMSCWarning
         (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
       method=ReadGenericMethod;
     if (image->compression == JPEGCompression)
-      method=GetJpegMethod(image,tiff,photometric,bits_per_sample,
+      method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
         samples_per_pixel);
-    if (image->compression == JBIGCompression)
+    if (compress_tag == COMPRESSION_JBIG)
       method=ReadStripMethod;
-    if ((photometric != PHOTOMETRIC_SEPARATED) &&
-
     if (TIFFIsTiled(tiff) != MagickFalse)
       method=ReadTileMethod;
     quantum_info->endian=LSBEndian;
     quantum_type=RGBQuantum;
-    pixels=GetQuantumPixels(quantum_info);
+    tiff_pixels=(unsigned char *) AcquireMagickMemory(MagickMax(
+      TIFFScanlineSize(tiff),(ssize_t) (image->columns*samples_per_pixel*
+      pow(2.0,ceil(log(bits_per_sample)/log(2.0))))));
+    if (tiff_pixels == (unsigned char *) NULL)
+      {
+        TIFFClose(tiff);
+        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      }
     switch (method)
     {
       case ReadSingleSampleMethod:
@@ -1449,52 +1630,6 @@ RestoreMSCWarning
         /*
           Convert TIFF image to PseudoClass MIFF image.
         */
-        if ((image->storage_class == PseudoClass) &&
-            (photometric == PHOTOMETRIC_PALETTE))
-          {
-            int
-              tiff_status;
-
-            size_t
-              range;
-
-            uint16
-              *blue_colormap,
-              *green_colormap,
-              *red_colormap;
-
-            /*
-              Initialize colormap.
-            */
-            tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
-              &green_colormap,&blue_colormap);
-            if (tiff_status == 1)
-              {
-                if ((red_colormap != (uint16 *) NULL) &&
-                    (green_colormap != (uint16 *) NULL) &&
-                    (blue_colormap != (uint16 *) NULL))
-                  {
-                    range=255;  /* might be old style 8-bit colormap */
-                    for (i=0; i < (ssize_t) image->colors; i++)
-                      if ((red_colormap[i] >= 256) ||
-                          (green_colormap[i] >= 256) ||
-                          (blue_colormap[i] >= 256))
-                        {
-                          range=65535;
-                          break;
-                        }
-                    for (i=0; i < (ssize_t) image->colors; i++)
-                    {
-                      image->colormap[i].red=ClampToQuantum(((double)
-                        QuantumRange*red_colormap[i])/range);
-                      image->colormap[i].green=ClampToQuantum(((double)
-                        QuantumRange*green_colormap[i])/range);
-                      image->colormap[i].blue=ClampToQuantum(((double)
-                        QuantumRange*blue_colormap[i])/range);
-                    }
-                  }
-              }
-          }
         quantum_type=IndexQuantum;
         pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
         if (image->alpha_trait != UndefinedPixelTrait)
@@ -1517,29 +1652,29 @@ RestoreMSCWarning
               quantum_type=GrayQuantum;
               pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0);
             }
-        status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
+        status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
+          bits_per_sample)/log(2))));
         if (status == MagickFalse)
           {
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
-        pixels=GetQuantumPixels(quantum_info);
         for (y=0; y < (ssize_t) image->rows; y++)
         {
           int
             status;
 
           register Quantum
-            *restrict q;
+            *magick_restrict q;
 
-          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
+          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
           if (status == -1)
             break;
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (Quantum *) NULL)
             break;
           (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
-            quantum_type,pixels,exception);
+            quantum_type,tiff_pixels,exception);
           if (SyncAuthenticPixels(image,exception) == MagickFalse)
             break;
           if (image->previous == (Image *) NULL)
@@ -1580,23 +1715,22 @@ RestoreMSCWarning
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
-        pixels=GetQuantumPixels(quantum_info);
         for (y=0; y < (ssize_t) image->rows; y++)
         {
           int
             status;
 
           register Quantum
-            *restrict q;
+            *magick_restrict q;
 
-          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
+          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
           if (status == -1)
             break;
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (Quantum *) NULL)
             break;
           (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
-            quantum_type,pixels,exception);
+            quantum_type,tiff_pixels,exception);
           if (SyncAuthenticPixels(image,exception) == MagickFalse)
             break;
           if (image->previous == (Image *) NULL)
@@ -1619,13 +1753,13 @@ RestoreMSCWarning
           for (y=0; y < (ssize_t) image->rows; y++)
           {
             register Quantum
-              *restrict q;
+              *magick_restrict q;
 
             int
               status;
 
             status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *)
-              pixels);
+              tiff_pixels);
             if (status == -1)
               break;
             q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
@@ -1651,7 +1785,7 @@ RestoreMSCWarning
                 default: quantum_type=UndefinedQuantum; break;
               }
             (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
-              quantum_type,pixels,exception);
+              quantum_type,tiff_pixels,exception);
             if (SyncAuthenticPixels(image,exception) == MagickFalse)
               break;
           }
@@ -1667,14 +1801,13 @@ RestoreMSCWarning
       }
       case ReadYCCKMethod:
       {
-        pixels=GetQuantumPixels(quantum_info);
         for (y=0; y < (ssize_t) image->rows; y++)
         {
           int
             status;
 
           register Quantum
-            *restrict q;
+            *magick_restrict q;
 
           register ssize_t
             x;
@@ -1682,13 +1815,13 @@ RestoreMSCWarning
           unsigned char
             *p;
 
-          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels);
+          status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) tiff_pixels);
           if (status == -1)
             break;
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (Quantum *) NULL)
             break;
-          p=pixels;
+          p=tiff_pixels;
           for (x=0; x < (ssize_t) image->columns; x++)
           {
             SetPixelCyan(image,ScaleCharToQuantum(ClampYCC((double) *p+
@@ -1730,20 +1863,20 @@ RestoreMSCWarning
             x;
 
           register Quantum
-            *restrict q;
+            *magick_restrict q;
 
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (Quantum *) NULL)
             break;
           if (i == 0)
             {
-              if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0)
+              if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0)
                 break;
               i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
                 image->rows-y);
             }
           i--;
-          p=((uint32 *) pixels)+image->columns*i;
+          p=((uint32 *) tiff_pixels)+image->columns*i;
           for (x=0; x < (ssize_t) image->columns; x++)
           {
             SetPixelRed(image,ScaleCharToQuantum((unsigned char)
@@ -1780,9 +1913,6 @@ RestoreMSCWarning
           columns,
           rows;
 
-        size_t
-          number_pixels;
-
         /*
           Convert tiled TIFF image to DirectClass MIFF image.
         */
@@ -1793,8 +1923,13 @@ RestoreMSCWarning
             ThrowReaderException(CoderError,"ImageIsNotTiled");
           }
         (void) SetImageStorageClass(image,DirectClass,exception);
-        number_pixels=columns*rows;
-        tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels,
+        number_pixels=(MagickSizeType) columns*rows;
+        if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
+          {
+            TIFFClose(tiff);
+            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+          }
+        tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
           sizeof(*tile_pixels));
         if (tile_pixels == (uint32 *) NULL)
           {
@@ -1807,8 +1942,8 @@ RestoreMSCWarning
             x;
 
           register Quantum
-            *restrict q,
-            *restrict tile;
+            *magick_restrict q,
+            *magick_restrict tile;
 
           size_t
             columns_remaining,
@@ -1896,8 +2031,7 @@ RestoreMSCWarning
           Convert TIFF image to DirectClass MIFF image.
         */
         number_pixels=(MagickSizeType) image->columns*image->rows;
-        if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t)
-            (number_pixels*sizeof(uint32))))
+        if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
           {
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
@@ -1910,8 +2044,8 @@ RestoreMSCWarning
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
         pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
-        (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
-          (uint32) image->rows,(uint32 *) pixels,0);
+        (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
+          image->rows,(uint32 *) pixels,0);
         /*
           Convert image to DirectClass pixel packets.
         */
@@ -1922,7 +2056,7 @@ RestoreMSCWarning
             x;
 
           register Quantum
-            *restrict q;
+            *magick_restrict q;
 
           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
           if (q == (Quantum *) NULL)
@@ -1930,11 +2064,12 @@ RestoreMSCWarning
           q+=GetPixelChannels(image)*(image->columns-1);
           for (x=0; x < (ssize_t) image->columns; x++)
           {
-            SetPixelRed(image,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)),q);
+            SetPixelRed(image,ScaleCharToQuantum((unsigned char)
+              TIFFGetR(*p)),q);
             SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
               TIFFGetG(*p)),q);
-            SetPixelBlue(image,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)),
-              q);
+            SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
+              TIFFGetB(*p)),q);
             if (image->alpha_trait != UndefinedPixelTrait)
               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
                 TIFFGetA(*p)),q);
@@ -1955,9 +2090,11 @@ RestoreMSCWarning
         break;
       }
     }
+    tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels);
     SetQuantumImageType(image,quantum_type);
   next_tiff_frame:
-    quantum_info=DestroyQuantumInfo(quantum_info);
+    if (quantum_info != (QuantumInfo *) NULL)
+      quantum_info=DestroyQuantumInfo(quantum_info);
     if (photometric == PHOTOMETRIC_CIELAB)
       DecodeLabImage(image,exception);
     if ((photometric == PHOTOMETRIC_LOGL) ||
@@ -1968,8 +2105,6 @@ RestoreMSCWarning
         if (bits_per_sample == 1)
           image->type=BilevelType;
       }
-    if (image->storage_class == PseudoClass)
-      image->depth=GetImageDepth(image,exception);
     /*
       Proceed to next image.
     */
@@ -1995,9 +2130,17 @@ RestoreMSCWarning
           break;
       }
   } while (status != MagickFalse);
-  (void) TIFFSetWarningHandler(warning_handler);
-  (void) TIFFSetErrorHandler(error_handler);
   TIFFClose(tiff);
+  TIFFReadPhotoshopLayers(image,image_info,exception);
+  if (image_info->number_scenes != 0)
+    {
+      if (image_info->scene >= GetImageListLength(image))
+        {
+          /* Subimage was not found in the Photoshop layer */
+          image=DestroyImageList(image);
+          return((Image *)NULL);
+        }
+    }
   return(GetFirstImageInList(image));
 }
 #endif
@@ -2079,7 +2222,7 @@ static void TIFFIgnoreTags(TIFF *tiff)
   i=0;
   p=tags;
   ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
-  // This also sets field_bit to 0 (FIELD_IGNORE)
+  /* This also sets field_bit to 0 (FIELD_IGNORE) */
   ResetMagickMemory(ignore,0,count*sizeof(*ignore));
   while (*p != '\0')
   {
@@ -2122,7 +2265,7 @@ ModuleExport size_t RegisterTIFFImage(void)
 #define TIFFDescription  "Tagged Image File Format"
 
   char
-    version[MaxTextExtent];
+    version[MagickPathExtent];
 
   MagickInfo
     *entry;
@@ -2132,8 +2275,10 @@ ModuleExport size_t RegisterTIFFImage(void)
   LockSemaphoreInfo(tiff_semaphore);
   if (instantiate_key == MagickFalse)
     {
-      if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)
+      if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
+      error_handler=TIFFSetErrorHandler(TIFFErrors);
+      warning_handler=TIFFSetWarningHandler(TIFFWarnings);
 #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
       if (tag_extender == (TIFFExtendProc) NULL)
         tag_extender=TIFFSetTagExtender(TIFFTagExtender);
@@ -2143,7 +2288,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   UnlockSemaphoreInfo(tiff_semaphore);
   *version='\0';
 #if defined(TIFF_VERSION)
-  (void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
+  (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION);
 #endif
 #if defined(MAGICKCORE_TIFF_DELEGATE)
   {
@@ -2154,78 +2299,78 @@ ModuleExport size_t RegisterTIFFImage(void)
       i;
 
     p=TIFFGetVersion();
-    for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
+    for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++)
       version[i]=(*p++);
     version[i]='\0';
   }
 #endif
 
-  entry=SetMagickInfo("GROUP4");
+  entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4");
 #if defined(MAGICKCORE_TIFF_DELEGATE)
   entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
   entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
 #endif
-  entry->raw=MagickTrue;
-  entry->endian_support=MagickTrue;
-  entry->adjoin=MagickFalse;
+  entry->flags|=CoderRawSupportFlag;
+  entry->flags|=CoderEndianSupportFlag;
+  entry->flags|=CoderDecoderSeekableStreamFlag;
+  entry->flags|=CoderEncoderSeekableStreamFlag;
+  entry->flags^=CoderAdjoinFlag;
+  entry->flags^=CoderUseExtensionFlag;
   entry->format_type=ImplicitFormatType;
-  entry->seekable_stream=MagickTrue;
-  entry->description=ConstantString("Raw CCITT Group4");
   entry->mime_type=ConstantString("image/tiff");
-  entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
-  entry=SetMagickInfo("PTIF");
+  entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF");
 #if defined(MAGICKCORE_TIFF_DELEGATE)
   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
   entry->encoder=(EncodeImageHandler *) WritePTIFImage;
 #endif
-  entry->endian_support=MagickTrue;
-  entry->seekable_stream=MagickTrue;
-  entry->description=ConstantString("Pyramid encoded TIFF");
+  entry->flags|=CoderEndianSupportFlag;
+  entry->flags|=CoderDecoderSeekableStreamFlag;
+  entry->flags|=CoderEncoderSeekableStreamFlag;
+  entry->flags^=CoderUseExtensionFlag;
   entry->mime_type=ConstantString("image/tiff");
-  entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
-  entry=SetMagickInfo("TIF");
+  entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription);
 #if defined(MAGICKCORE_TIFF_DELEGATE)
   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
 #endif
-  entry->endian_support=MagickTrue;
-  entry->seekable_stream=MagickTrue;
-  entry->stealth=MagickTrue;
-  entry->description=ConstantString(TIFFDescription);
+  entry->flags|=CoderEndianSupportFlag;
+  entry->flags|=CoderDecoderSeekableStreamFlag;
+  entry->flags|=CoderEncoderSeekableStreamFlag;
+  entry->flags|=CoderStealthFlag;
+  entry->flags^=CoderUseExtensionFlag;
   if (*version != '\0')
     entry->version=ConstantString(version);
   entry->mime_type=ConstantString("image/tiff");
-  entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
-  entry=SetMagickInfo("TIFF");
+  entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription);
 #if defined(MAGICKCORE_TIFF_DELEGATE)
   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
 #endif
   entry->magick=(IsImageFormatHandler *) IsTIFF;
-  entry->endian_support=MagickTrue;
-  entry->seekable_stream=MagickTrue;
-  entry->description=ConstantString(TIFFDescription);
+  entry->flags|=CoderEndianSupportFlag;
+  entry->flags|=CoderDecoderSeekableStreamFlag;
+  entry->flags|=CoderEncoderSeekableStreamFlag;
+  entry->flags^=CoderUseExtensionFlag;
   if (*version != '\0')
     entry->version=ConstantString(version);
   entry->mime_type=ConstantString("image/tiff");
-  entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
-  entry=SetMagickInfo("TIFF64");
+  entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)");
 #if defined(TIFF_VERSION_BIG)
   entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
   entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
 #endif
-  entry->adjoin=MagickFalse;
-  entry->endian_support=MagickTrue;
-  entry->seekable_stream=MagickTrue;
-  entry->description=ConstantString("Tagged Image File Format (64-bit)");
+  entry->flags|=CoderEndianSupportFlag;
+  entry->flags|=CoderDecoderSeekableStreamFlag;
+  entry->flags|=CoderEncoderSeekableStreamFlag;
+  entry->flags^=CoderAdjoinFlag;
+  entry->flags^=CoderUseExtensionFlag;
   if (*version != '\0')
     entry->version=ConstantString(version);
   entry->mime_type=ConstantString("image/tiff");
-  entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   return(MagickImageCoderSignature);
 }
@@ -2264,8 +2409,10 @@ ModuleExport void UnregisterTIFFImage(void)
       if (tag_extender == (TIFFExtendProc) NULL)
         (void) TIFFSetTagExtender(tag_extender);
 #endif
-      if (MagickDeleteThreadKey(tiff_exception) == MagickFalse)
+      if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
+      (void) TIFFSetWarningHandler(warning_handler);
+      (void) TIFFSetErrorHandler(error_handler);
       instantiate_key=MagickFalse;
     }
   UnlockSemaphoreInfo(tiff_semaphore);
@@ -2304,7 +2451,7 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
   Image *image,ExceptionInfo *exception)
 {
   char
-    filename[MaxTextExtent];
+    filename[MagickPathExtent];
 
   FILE
     *file;
@@ -2341,13 +2488,13 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
     Write image as CCITT Group4 TIFF image to a temporary file.
   */
   assert(image_info != (const ImageInfo *) NULL);
-  assert(image_info->signature == MagickSignature);
+  assert(image_info->signature == MagickCoreSignature);
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
+  assert(exception->signature == MagickCoreSignature);
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
@@ -2368,11 +2515,13 @@ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
         filename);
       return(MagickFalse);
     }
-  (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
+  (void) FormatLocaleString(huffman_image->filename,MagickPathExtent,"tiff:%s",
     filename);
   (void) SetImageType(huffman_image,BilevelType,exception);
   write_info=CloneImageInfo((ImageInfo *) NULL);
   SetImageInfoFile(write_info,file);
+  (void) SetImageDepth(image,1,exception);
+  (void) SetImageType(image,BilevelType,exception);
   write_info->compression=Group4Compression;
   write_info->type=BilevelType;
   (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
@@ -2501,8 +2650,11 @@ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
       *clone_image;
 
     clone_image=CloneImage(next,0,0,MagickFalse,exception);
+    if (clone_image == (Image *) NULL)
+      break;
     clone_image->previous=NewImageList();
     clone_image->next=NewImageList();
+    (void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
     AppendImageToList(&images,clone_image);
     columns=next->columns;
     rows=next->rows;
@@ -2517,20 +2669,26 @@ static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
       if (pyramid_image == (Image *) NULL)
         break;
       pyramid_image->resolution=resolution;
+      (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
+        exception);
       AppendImageToList(&images,pyramid_image);
     }
   }
-  images=GetFirstImageInList(images);
-  /*
-    Write pyramid-encoded TIFF image.
-  */
-  write_info=CloneImageInfo(image_info);
-  write_info->adjoin=MagickTrue;
-  (void) CopyMagickString(write_info->magick,"TIFF",MaxTextExtent);
-  (void) CopyMagickString(images->magick,"TIFF",MaxTextExtent);
-  status=WriteTIFFImage(write_info,images,exception);
-  images=DestroyImageList(images);
-  write_info=DestroyImageInfo(write_info);
+  status=MagickFalse;
+  if (images != (Image *) NULL)
+    {
+      /*
+        Write pyramid-encoded TIFF image.
+      */
+      images=GetFirstImageInList(images);
+      write_info=CloneImageInfo(image_info);
+      write_info->adjoin=MagickTrue;
+      (void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
+      (void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
+      status=WriteTIFFImage(write_info,images,exception);
+      images=DestroyImageList(images);
+      write_info=DestroyImageInfo(write_info);
+    }
   return(status);
 }
 #endif
@@ -2601,7 +2759,7 @@ static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -2654,7 +2812,23 @@ static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
   (void) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info));
   option=GetImageOption(image_info,"tiff:tile-geometry");
   if (option == (const char *) NULL)
-    return(MagickTrue);
+    {
+      uint32
+        rows_per_strip;
+
+      option=GetImageOption(image_info,"tiff:rows-per-strip");
+      if (option != (const char *) NULL)
+        rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
+      else
+        if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0)
+          rows_per_strip=0;  /* use default */
+      rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip);
+      (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
+      return(MagickTrue);
+    }
+  /*
+    Create tiled TIFF, ignore "tiff:rows-per-strip".
+  */
   flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
   if ((flags & HeightValue) == 0)
     tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
@@ -2816,7 +2990,8 @@ static void TIFFSetProfiles(TIFF *tiff,Image *image)
   }
 }
 
-static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
+static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
+  Image *image,ExceptionInfo *exception)
 {
   const char
     *value;
@@ -2851,12 +3026,36 @@ static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
   value=GetImageArtifact(image,"kodak-36867");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,36867,value);
-  value=GetImageArtifact(image,"label");
+  value=GetImageProperty(image,"label",exception);
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
-  value=GetImageArtifact(image,"comment");
+  value=GetImageProperty(image,"comment",exception);
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
+  value=GetImageArtifact(image,"tiff:subfiletype");
+  if (value != (const char *) NULL)
+    {
+      if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
+        (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
+      else
+        if (LocaleCompare(value,"PAGE") == 0)
+          (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
+        else
+          if (LocaleCompare(value,"MASK") == 0)
+            (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
+    }
+  else
+    {
+      uint16
+        page,
+        pages;
+
+      page=(uint16) image->scene;
+      pages=(uint16) GetImageListLength(image);
+      if ((image_info->adjoin != MagickFalse) && (pages > 1))
+        (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
+      (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
+    }
 }
 
 static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
@@ -2931,10 +3130,6 @@ static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
 static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   Image *image,ExceptionInfo *exception)
 {
-#if !defined(TIFFDefaultStripSize)
-#define TIFFDefaultStripSize(tiff,request)  (8192UL/TIFFScanlineSize(tiff))
-#endif
-
   const char
     *mode,
     *option;
@@ -2970,10 +3165,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   TIFF
     *tiff;
 
-  TIFFErrorHandler
-    error_handler,
-    warning_handler;
-
   TIFFInfo
     tiff_info;
 
@@ -2983,9 +3174,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     endian,
     photometric;
 
-  uint32
-    rows_per_strip;
-
   unsigned char
     *pixels;
 
@@ -2993,19 +3181,17 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     Open TIFF file.
   */
   assert(image_info != (const ImageInfo *) NULL);
-  assert(image_info->signature == MagickSignature);
+  assert(image_info->signature == MagickCoreSignature);
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
+  assert(exception->signature == MagickCoreSignature);
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
-  (void) MagickSetThreadValue(tiff_exception,exception);
-  error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
-  warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
+  (void) SetMagickThreadValue(tiff_exception,exception);
   endian_type=UndefinedEndian;
   option=GetImageOption(image_info,"tiff:endian");
   if (option != (const char *) NULL)
@@ -3034,11 +3220,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
     TIFFUnmapBlob);
   if (tiff == (TIFF *) NULL)
-    {
-      (void) TIFFSetWarningHandler(warning_handler);
-      (void) TIFFSetErrorHandler(error_handler);
-      return(MagickFalse);
-    }
+    return(MagickFalse);
   scene=0;
   debug=IsEventLogging();
   (void) debug;
@@ -3061,6 +3243,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       case Group4Compression:
       {
         (void) SetImageType(image,BilevelType,exception);
+        (void) SetImageDepth(image,1,exception);
         break;
       }
       case JPEGCompression:
@@ -3219,24 +3402,18 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
             photometric=PHOTOMETRIC_RGB;
         (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
         if ((image_info->type != TrueColorType) &&
-            (image_info->type != TrueColorMatteType))
+            (image_info->type != TrueColorAlphaType))
           {
             if ((image_info->type != PaletteType) &&
-                (IsImageGray(image,exception) != MagickFalse))
+                (SetImageGray(image,exception) != MagickFalse))
               {
                 photometric=(uint16) (quantum_info->min_is_white !=
                   MagickFalse ? PHOTOMETRIC_MINISWHITE :
                   PHOTOMETRIC_MINISBLACK);
                 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
-                if ((image_info->depth == 0) &&
-                    (image->alpha_trait == UndefinedPixelTrait) &&
-                    (IsImageMonochrome(image,exception) != MagickFalse))
-                  {
-                    status=SetQuantumDepth(image,quantum_info,1);
-                    if (status == MagickFalse)
-                      ThrowWriterException(ResourceLimitError,
-                        "MemoryAllocationFailed");
-                  }
+                if ((image->depth == 1) &&
+                    (image->alpha_trait == UndefinedPixelTrait))
+                  SetImageMonochrome(image,exception);
               }
             else
               if (image->storage_class == PseudoClass)
@@ -3342,25 +3519,13 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       if ((image_info->interlace == PlaneInterlace) ||
           (image_info->interlace == PartitionInterlace))
         (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
-     rows_per_strip=TIFFDefaultStripSize(tiff,0);
-    option=GetImageOption(image_info,"tiff:rows-per-strip");
-    if (option != (const char *) NULL)
-      rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
     switch (compress_tag)
     {
       case COMPRESSION_JPEG:
       {
 #if defined(JPEG_SUPPORT)
-        const char
-          *sampling_factor;
 
-        GeometryInfo
-          geometry_info;
 
-        MagickStatusType
-          flags;
-
-        rows_per_strip+=(16-(rows_per_strip % 16));
         if (image_info->quality != UndefinedCompressionQuality)
           (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
         (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
@@ -3370,26 +3535,37 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
               *value;
 
             (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
-            sampling_factor=(const char *) NULL;
-            value=GetImageProperty(image,"jpeg:sampling-factor",exception);
-            if (value != (char *) NULL)
+            if (image->colorspace == YCbCrColorspace)
               {
-                sampling_factor=value;
-                if (image->debug != MagickFalse)
-                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
-                    "  Input sampling-factors=%s",sampling_factor);
-              }
-            if (image_info->sampling_factor != (char *) NULL)
-              sampling_factor=image_info->sampling_factor;
-            if (sampling_factor != (const char *) NULL)
-              {
-                flags=ParseGeometry(sampling_factor,&geometry_info);
-                if ((flags & SigmaValue) == 0)
-                  geometry_info.sigma=geometry_info.rho;
-                if (image->colorspace == YCbCrColorspace)
-                  (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
-                    geometry_info.rho,(uint16) geometry_info.sigma);
-              }
+                const char
+                  *sampling_factor;
+
+                GeometryInfo
+                  geometry_info;
+
+                MagickStatusType
+                  flags;
+
+                sampling_factor=(const char *) NULL;
+                value=GetImageProperty(image,"jpeg:sampling-factor",exception);
+                if (value != (char *) NULL)
+                  {
+                    sampling_factor=value;
+                    if (image->debug != MagickFalse)
+                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
+                        "  Input sampling-factors=%s",sampling_factor);
+                  }
+                if (image_info->sampling_factor != (char *) NULL)
+                  sampling_factor=image_info->sampling_factor;
+                if (sampling_factor != (const char *) NULL)
+                  {
+                    flags=ParseGeometry(sampling_factor,&geometry_info);
+                    if ((flags & SigmaValue) == 0)
+                      geometry_info.sigma=geometry_info.rho;
+                    (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
+                      geometry_info.rho,(uint16) geometry_info.sigma);
+                  }
+                }
           }
         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
           &bits_per_sample);
@@ -3400,7 +3576,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       }
       case COMPRESSION_ADOBE_DEFLATE:
       {
-        rows_per_strip=(uint32) image->rows;
         (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
           &bits_per_sample);
         if (((photometric == PHOTOMETRIC_RGB) ||
@@ -3417,15 +3592,11 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         /*
           Byte-aligned EOL.
         */
-        rows_per_strip=(uint32) image->rows;
         (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
         break;
       }
       case COMPRESSION_CCITTFAX4:
-      {
-        rows_per_strip=(uint32) image->rows;
         break;
-      }
 #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
       case COMPRESSION_LZMA:
       {
@@ -3452,11 +3623,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       default:
         break;
     }
-    if (rows_per_strip < 1)
-      rows_per_strip=1;
-    if ((image->rows/rows_per_strip) >= (1UL << 15))
-      rows_per_strip=(uint32) (image->rows >> 15);
-    (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
     if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0))
       {
         unsigned short
@@ -3535,7 +3701,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
     }
-    (void) TIFFSetProperties(tiff,image,exception);
+    (void) TIFFSetProperties(tiff,image_info,image,exception);
 DisableMSCWarning(4127)
     if (0)
 RestoreMSCWarning
@@ -3546,8 +3712,8 @@ RestoreMSCWarning
     if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
     quantum_info->endian=LSBEndian;
-    pixels=GetQuantumPixels(quantum_info);
-    tiff_info.scanline=GetQuantumPixels(quantum_info);
+    pixels=(unsigned char *) GetQuantumPixels(quantum_info);
+    tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info);
     switch (photometric)
     {
       case PHOTOMETRIC_CIELAB:
@@ -3568,7 +3734,7 @@ RestoreMSCWarning
             for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const Quantum
-                *restrict p;
+                *magick_restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
               if (p == (const Quantum *) NULL)
@@ -3597,7 +3763,7 @@ RestoreMSCWarning
             for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const Quantum
-                *restrict p;
+                *magick_restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
               if (p == (const Quantum *) NULL)
@@ -3616,7 +3782,7 @@ RestoreMSCWarning
             for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const Quantum
-                *restrict p;
+                *magick_restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
               if (p == (const Quantum *) NULL)
@@ -3635,7 +3801,7 @@ RestoreMSCWarning
             for (y=0; y < (ssize_t) image->rows; y++)
             {
               register const Quantum
-                *restrict p;
+                *magick_restrict p;
 
               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
               if (p == (const Quantum *) NULL)
@@ -3655,7 +3821,7 @@ RestoreMSCWarning
               for (y=0; y < (ssize_t) image->rows; y++)
               {
                 register const Quantum
-                  *restrict p;
+                  *magick_restrict p;
 
                 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
                 if (p == (const Quantum *) NULL)
@@ -3689,7 +3855,7 @@ RestoreMSCWarning
         for (y=0; y < (ssize_t) image->rows; y++)
         {
           register const Quantum
-            *restrict p;
+            *magick_restrict p;
 
           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
           if (p == (const Quantum *) NULL)
@@ -3760,7 +3926,7 @@ RestoreMSCWarning
         for (y=0; y < (ssize_t) image->rows; y++)
         {
           register const Quantum
-            *restrict p;
+            *magick_restrict p;
 
           p=GetVirtualPixels(image,0,y,image->columns,1,exception);
           if (p == (const Quantum *) NULL)
@@ -3797,8 +3963,6 @@ RestoreMSCWarning
     if (status == MagickFalse)
       break;
   } while (image_info->adjoin != MagickFalse);
-  (void) TIFFSetWarningHandler(warning_handler);
-  (void) TIFFSetErrorHandler(error_handler);
   TIFFClose(tiff);
   return(MagickTrue);
 }