]> granicus.if.org Git - imagemagick/blobdiff - coders/tiff.c
(no commit message)
[imagemagick] / coders / tiff.c
index d9793821cf0ae00bd555deea8b7b4ad900080379..5bf4489fb96a9cf71c7056ea3f6a8b1505593105 100644 (file)
 %                        Read/Write TIFF Image Format                         %
 %                                                                             %
 %                              Software Design                                %
-%                                John Cristy                                  %
+%                                   Cristy                                    %
 %                                 July 1992                                   %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2014 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  %
@@ -98,7 +98,7 @@
 #  define TIFFTAG_COPYRIGHT  33432
 # endif
 # if !defined(TIFFTAG_OPIIMAGEID)
-#  define TIFF_OPIIMAGEID  32781
+#  define TIFFTAG_OPIIMAGEID  32781
 # endif
 \f
 /*
@@ -109,7 +109,8 @@ typedef struct _ExifInfo
 {
   unsigned int
     tag,
-    type;
+    type,
+    variable_length;
 
   const char
     *property;
@@ -117,64 +118,62 @@ typedef struct _ExifInfo
 
 static const ExifInfo
   exif_info[] = {
-    { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, "exif:ExposureTime" },
-    { EXIFTAG_FNUMBER, TIFF_RATIONAL, "exif:FNumber" },
-    { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, "exif:ExposureProgram" },
-    { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, "exif:SpectralSensitivity" },
-    { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, "exif:ISOSpeedRatings" },
-    { EXIFTAG_OECF, TIFF_NOTYPE, "exif:OptoelectricConversionFactor" },
-    { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, "exif:ExifVersion" },
-    { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, "exif:DateTimeOriginal" },
-    { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, "exif:DateTimeDigitized" },
-    { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, "exif:ComponentsConfiguration" },
-    { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, "exif:CompressedBitsPerPixel" },
-    { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, "exif:ShutterSpeedValue" },
-    { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, "exif:ApertureValue" },
-    { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, "exif:BrightnessValue" },
-    { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, "exif:ExposureBiasValue" },
-    { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, "exif:MaxApertureValue" },
-    { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, "exif:SubjectDistance" },
-    { EXIFTAG_METERINGMODE, TIFF_SHORT, "exif:MeteringMode" },
-    { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, "exif:LightSource" },
-    { EXIFTAG_FLASH, TIFF_SHORT, "exif:Flash" },
-    { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, "exif:FocalLength" },
-    { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, "exif:SubjectArea" },
-    { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, "exif:MakerNote" },
-    { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, "exif:UserComment" },
-    { EXIFTAG_SUBSECTIME, TIFF_ASCII, "exif:SubSecTime" },
-    { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, "exif:SubSecTimeOriginal" },
-    { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, "exif:SubSecTimeDigitized" },
-    { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, "exif:FlashpixVersion" },
-    { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, "exif:PixelXDimension" },
-    { EXIFTAG_PIXELXDIMENSION, TIFF_SHORT, "exif:PixelXDimension" },
-    { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, "exif:PixelYDimension" },
-    { EXIFTAG_PIXELYDIMENSION, TIFF_SHORT, "exif:PixelYDimension" },
-    { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, "exif:RelatedSoundFile" },
-    { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, "exif:FlashEnergy" },
-    { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, "exif:SpatialFrequencyResponse" },
-    { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneXResolution" },
-    { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, "exif:FocalPlaneYResolution" },
-    { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, "exif:FocalPlaneResolutionUnit" },
-    { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, "exif:SubjectLocation" },
-    { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, "exif:ExposureIndex" },
-    { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, "exif:SensingMethod" },
-    { EXIFTAG_FILESOURCE, TIFF_NOTYPE, "exif:FileSource" },
-    { EXIFTAG_SCENETYPE, TIFF_NOTYPE, "exif:SceneType" },
-    { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, "exif:CFAPattern" },
-    { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, "exif:CustomRendered" },
-    { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, "exif:ExposureMode" },
-    { EXIFTAG_WHITEBALANCE, TIFF_SHORT, "exif:WhiteBalance" },
-    { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, "exif:DigitalZoomRatio" },
-    { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, "exif:FocalLengthIn35mmFilm" },
-    { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, "exif:SceneCaptureType" },
-    { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, "exif:GainControl" },
-    { EXIFTAG_CONTRAST, TIFF_SHORT, "exif:Contrast" },
-    { EXIFTAG_SATURATION, TIFF_SHORT, "exif:Saturation" },
-    { EXIFTAG_SHARPNESS, TIFF_SHORT, "exif:Sharpness" },
-    { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, "exif:DeviceSettingDescription" },
-    { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, "exif:SubjectDistanceRange" },
-    { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, "exif:ImageUniqueID" },
-    { 0, 0, (char *) NULL }
+    { EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
+    { EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
+    { EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
+    { EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
+    { EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
+    { EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
+    { EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
+    { EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
+    { EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
+    { EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
+    { EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
+    { EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
+    { EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
+    { EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
+    { EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
+    { EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
+    { EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
+    { EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
+    { EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
+    { EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
+    { EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
+    { EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
+    { EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
+    { EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
+    { EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
+    { EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
+    { EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
+    { EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
+    { EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
+    { EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
+    { EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
+    { EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
+    { EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
+    { EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
+    { EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
+    { EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
+    { EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
+    { EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
+    { EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
+    { EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
+    { EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
+    { EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
+    { EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
+    { EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
+    { EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
+    { EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
+    { EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
+    { EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
+    { EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
+    { EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
+    { EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
+    { EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
+    { EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
+    { EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
+    { EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
+    { 0, 0, 0, (char *) NULL }
 };
 #endif
 #endif  /* MAGICKCORE_TIFF_DELEGATE */
@@ -602,6 +601,8 @@ static void TIFFGetProfiles(TIFF *tiff,Image *image,ExceptionInfo *exception)
   length=0;
   if (TIFFGetField(tiff,37724,&length,&profile) == 1)
     (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
+  if (TIFFGetField(tiff,34118,&length,&profile) == 1)
+    (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length,exception);
 }
 
 static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
@@ -687,7 +688,10 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
     return;
   directory=TIFFCurrentDirectory(tiff);
   if (TIFFReadEXIFDirectory(tiff,offset) == 0)
-    return;
+    {
+      directory=TIFFCurrentDirectory(tiff);
+      return;
+    }
   sans=NULL;
   for (i=0; exif_info[i].tag != 0; i++)
   {
@@ -707,11 +711,23 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
       }
       case TIFF_SHORT:
       {
-        uint16
-          shorty[2] = { 0, 0};
+        if (exif_info[i].variable_length != 0)
+          {
+            uint16
+              *shorty;
+
+            if (TIFFGetField(tiff,exif_info[i].tag,&sans,&shorty,&sans,&sans) != 0)
+              (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty[0]);
+          }
+        else
+          {
+            uint16
+              shorty;
 
-        if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) != 0)
-          (void) FormatLocaleString(value,MaxTextExtent,"%d",(int) shorty[0]);
+            shorty=0;
+            if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) != 0)
+              (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
+          }
         break;
       }
       case TIFF_LONG:
@@ -719,6 +735,7 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
         uint32
           longy;
 
+        longy=0;
         if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) != 0)
           (void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
         break;
@@ -727,24 +744,35 @@ static void TIFFGetEXIFProperties(TIFF *tiff,Image *image,
       case TIFF_LONG8:
       {
         uint64
-          longy;
+          long8y;
 
-        if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) != 0)
+        long8y=0;
+        if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) != 0)
           (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
-            ((MagickOffsetType) longy));
+            ((MagickOffsetType) long8y));
         break;
       }
 #endif
       case TIFF_RATIONAL:
       case TIFF_SRATIONAL:
       case TIFF_FLOAT:
-      case TIFF_DOUBLE:
       {
         float
-          rational[16];
+          floaty;
 
-        if (TIFFGetField(tiff,exif_info[i].tag,&rational,&sans,&sans) != 0)
-          (void) FormatLocaleString(value,MaxTextExtent,"%g",rational[0]);
+        floaty=0.0;
+        if (TIFFGetField(tiff,exif_info[i].tag,&floaty,&sans,&sans) != 0)
+          (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
+        break;
+      }
+      case TIFF_DOUBLE:
+      {
+        double
+          doubley;
+
+        doubley=0.0;
+        if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) != 0)
+          (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
         break;
       }
       default:
@@ -973,7 +1001,9 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     }
   do
   {
+DisableMSCWarning(4127)
     if (0 && (image_info->verbose != MagickFalse))
+RestoreMSCWarning
       TIFFPrintDirectory(tiff,stdout,MagickFalse);
 #if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
     (void) SetImageProperty(image,"tiff:endian",TIFFIsBigEndian(tiff) == 0 ?
@@ -1070,6 +1100,11 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       SetImageColorspace(image,CMYKColorspace,exception);
     if (photometric == PHOTOMETRIC_CIELAB)
       SetImageColorspace(image,LabColorspace,exception);
+    TIFFGetProfiles(tiff,image,exception);
+    TIFFGetProperties(tiff,image,exception);
+    option=GetImageOption(image_info,"tiff:exif-properties");
+    if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
+      TIFFGetEXIFProperties(tiff,image,exception);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
       &samples_per_pixel);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units);
@@ -1079,8 +1114,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution);
     image->resolution.x=x_resolution;
     image->resolution.y=y_resolution;
-    x_position=(float) MagickEpsilonReciprocal(x_resolution)*image->page.x;
-    y_position=(float) MagickEpsilonReciprocal(y_resolution)*image->page.y;
+    x_position=(float) PerceptibleReciprocal(x_resolution)*image->page.x;
+    y_position=(float) PerceptibleReciprocal(y_resolution)*image->page.y;
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position);
     (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position);
     image->page.x=(ssize_t) ceil(x_position*x_resolution-0.5);
@@ -1137,12 +1172,6 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
              sampling_factor,exception);
            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
              "Sampling Factors: %s",sampling_factor);
-           if ((samples_per_pixel > 1) && (photometric == PHOTOMETRIC_YCBCR))
-             {
-               (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,
-                 JPEGCOLORMODE_RGB);
-               photometric=PHOTOMETRIC_RGB;
-             }
          }
 #endif
         break;
@@ -1156,11 +1185,6 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
       default: image->compression=RLECompression; break;
     }
-    TIFFGetProfiles(tiff,image,exception);
-    TIFFGetProperties(tiff,image,exception);
-    option=GetImageOption(image_info,"tiff:exif-properties");
-    if (IfMagickTrue(IsStringNotFalse(option))) /* enabled by default */
-      TIFFGetEXIFProperties(tiff,image,exception);
     /*
       Allocate memory for the image and pixel buffer.
     */
@@ -1276,6 +1300,8 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
     if ((photometric != PHOTOMETRIC_SEPARATED) &&
         (interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
       method=ReadGenericMethod;
+    if (image->compression == JPEGCompression)
+      method=ReadGenericMethod;
     if (TIFFIsTiled(tiff) != MagickFalse)
       method=ReadTileMethod;
     quantum_info->endian=LSBEndian;
@@ -1670,6 +1696,9 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       case ReadGenericMethod:
       default:
       {
+        MemoryInfo
+          *pixel_info;
+
         register uint32
           *p;
 
@@ -1686,13 +1715,14 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
-        pixels=(uint32 *) AcquireQuantumMemory(image->columns,image->rows*
+        pixel_info=AcquireVirtualMemory(image->columns,image->rows*
           sizeof(uint32));
-        if (pixels == (uint32 *) NULL)
+        if (pixel_info == (MemoryInfo *) NULL)
           {
             TIFFClose(tiff);
             ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
           }
+        pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
         (void) TIFFReadRGBAImage(tiff,(uint32) image->columns,
           (uint32) image->rows,(uint32 *) pixels,0);
         /*
@@ -1713,17 +1743,17 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
           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 == BlendPixelTrait)
               SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
                 TIFFGetA(*p)),q);
             p--;
-            q-=GetPixelChannels(image);;
+            q-=GetPixelChannels(image);
           }
           if (SyncAuthenticPixels(image,exception) == MagickFalse)
             break;
@@ -1735,7 +1765,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
                 break;
             }
         }
-        pixels=(uint32 *) RelinquishMagickMemory(pixels);
+        pixel_info=RelinquishVirtualMemory(pixel_info);
         break;
       }
     }
@@ -1754,14 +1784,6 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       }
     if (image->storage_class == PseudoClass)
       image->depth=GetImageDepth(image,exception);
-    if ((photometric == PHOTOMETRIC_LOGL) ||
-        (photometric == PHOTOMETRIC_MINISBLACK) ||
-        (photometric == PHOTOMETRIC_MINISWHITE))
-      {
-         image->type=GrayscaleType;
-         if (bits_per_sample == 1)
-           image->type=BilevelType;
-      }
     /*
       Proceed to next image.
     */
@@ -1769,7 +1791,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
         break;
     status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
-    if (status == MagickTrue)
+    if (status != MagickFalse)
       {
         /*
           Allocate next image structure.
@@ -1786,7 +1808,7 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
         if (status == MagickFalse)
           break;
       }
-  } while (status == MagickTrue);
+  } while (status != MagickFalse);
   (void) TIFFSetWarningHandler(warning_handler);
   (void) TIFFSetErrorHandler(error_handler);
   TIFFClose(tiff);
@@ -1822,21 +1844,90 @@ static Image *ReadTIFFImage(const ImageInfo *image_info,
 static TIFFExtendProc
   tag_extender = (TIFFExtendProc) NULL;
 
+static void TIFFIgnoreTags(TIFF *tiff)
+{
+  char
+    *q;
+
+  const char
+    *p,
+    *tags;
+
+  Image
+   *image;
+
+  register ssize_t
+    i;
+
+  size_t
+    count;
+
+  TIFFFieldInfo
+    *ignore;
+
+  if (TIFFGetReadProc(tiff) != TIFFReadBlob)
+    return;
+  image=(Image *)TIFFClientdata(tiff);
+  tags=GetImageArtifact(image,"tiff:ignore-tags");
+  if (tags == (const char *) NULL)
+    return;
+  count=0;
+  p=tags;
+  while (*p != '\0')
+  {
+    while ((isspace((int) ((unsigned char) *p)) != 0))
+      p++;
+
+    (void) strtol(p,&q,10);
+    if (p == q)
+      return;
+
+    p=q;
+    count++;
+
+    while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
+      p++;
+  }
+  if (count == 0)
+    return;
+  i=0;
+  p=tags;
+  ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
+  // This also sets field_bit to 0 (FIELD_IGNORE)
+  ResetMagickMemory(ignore,0,count*sizeof(*ignore));
+  while (*p != '\0')
+  {
+    while ((isspace((int) ((unsigned char) *p)) != 0))
+      p++;
+
+    ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
+
+    p=q;
+    i++;
+
+    while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
+      p++;
+  }
+  (void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
+  ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
+}
+
 static void TIFFTagExtender(TIFF *tiff)
 {
   static const TIFFFieldInfo
     TIFFExtensions[] =
     {
-      {
-        37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
-          (char *) "PhotoshopLayerData"
-      }
+      { 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
+        (char *) "PhotoshopLayerData" },
+      { 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
+        (char *) "Microscope" }
     };
 
   TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
     sizeof(*TIFFExtensions));
   if (tag_extender != (TIFFExtendProc) NULL)
     (*tag_extender)(tiff);
+  TIFFIgnoreTags(tiff);
 }
 #endif
 
@@ -1851,7 +1942,7 @@ ModuleExport size_t RegisterTIFFImage(void)
     *entry;
 
   if (tiff_semaphore == (SemaphoreInfo *) NULL)
-    tiff_semaphore=AllocateSemaphoreInfo();
+    ActivateSemaphoreInfo(&tiff_semaphore);
   LockSemaphoreInfo(tiff_semaphore);
   if (instantiate_key == MagickFalse)
     {
@@ -1895,6 +1986,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   entry->seekable_stream=MagickTrue;
   entry->thread_support=NoThreadSupport;
   entry->description=ConstantString("Raw CCITT Group4");
+  entry->mime_type=ConstantString("image/tiff");
   entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   entry=SetMagickInfo("PTIF");
@@ -1906,6 +1998,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   entry->seekable_stream=MagickTrue;
   entry->thread_support=NoThreadSupport;
   entry->description=ConstantString("Pyramid encoded TIFF");
+  entry->mime_type=ConstantString("image/tiff");
   entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   entry=SetMagickInfo("TIF");
@@ -1920,6 +2013,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   entry->description=ConstantString(TIFFDescription);
   if (*version != '\0')
     entry->version=ConstantString(version);
+  entry->mime_type=ConstantString("image/tiff");
   entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   entry=SetMagickInfo("TIFF");
@@ -1934,6 +2028,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   entry->description=ConstantString(TIFFDescription);
   if (*version != '\0')
     entry->version=ConstantString(version);
+  entry->mime_type=ConstantString("image/tiff");
   entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   entry=SetMagickInfo("TIFF64");
@@ -1948,6 +2043,7 @@ ModuleExport size_t RegisterTIFFImage(void)
   entry->description=ConstantString("Tagged Image File Format (64-bit)");
   if (*version != '\0')
     entry->version=ConstantString(version);
+  entry->mime_type=ConstantString("image/tiff");
   entry->module=ConstantString("TIFF");
   (void) RegisterMagickInfo(entry);
   return(MagickImageCoderSignature);
@@ -1979,7 +2075,7 @@ ModuleExport void UnregisterTIFFImage(void)
   (void) UnregisterMagickInfo("TIF");
   (void) UnregisterMagickInfo("PTIF");
   if (tiff_semaphore == (SemaphoreInfo *) NULL)
-    tiff_semaphore=AllocateSemaphoreInfo();
+    ActivateSemaphoreInfo(&tiff_semaphore);
   LockSemaphoreInfo(tiff_semaphore);
   if (instantiate_key != MagickFalse)
     {
@@ -1992,7 +2088,7 @@ ModuleExport void UnregisterTIFFImage(void)
       instantiate_key=MagickFalse;
     }
   UnlockSemaphoreInfo(tiff_semaphore);
-  DestroySemaphoreInfo(&tiff_semaphore);
+  RelinquishSemaphoreInfo(&tiff_semaphore);
 }
 \f
 #if defined(MAGICKCORE_TIFF_DELEGATE)
@@ -2354,8 +2450,8 @@ static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
   return(status);
 }
 
-static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
-  TIFFInfo *tiff_info)
+static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,
+  TIFF *tiff,TIFFInfo *tiff_info)
 {
   const char
     *option;
@@ -2484,6 +2580,11 @@ static void TIFFSetProfiles(TIFF *tiff,Image *image)
   for (name=GetNextImageProfile(image); name != (const char *) NULL; )
   {
     profile=GetImageProfile(image,name);
+    if (GetStringInfoLength(profile) == 0)
+      {
+        name=GetNextImageProfile(image);
+        continue;
+      }
 #if defined(TIFFTAG_XMLPACKET)
     if (LocaleCompare(name,"xmp") == 0)
       (void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
@@ -2521,6 +2622,9 @@ static void TIFFSetProfiles(TIFF *tiff,Image *image)
     if (LocaleCompare(name,"tiff:37724") == 0)
       (void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
         GetStringInfoDatum(profile));
+    if (LocaleCompare(name,"tiff:34118") == 0)
+      (void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
+        GetStringInfoDatum(profile));
     name=GetNextImageProfile(image);
   }
 }
@@ -2530,38 +2634,40 @@ static void TIFFSetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception)
   const char
     *value;
 
-  (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,image->filename);
-  value=GetImageProperty(image,"tiff:hostcomputer",exception);
+  value=GetImageArtifact(image,"tiff:document");
+  if (value != (const char *) NULL)
+    (void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
+  value=GetImageArtifact(image,"tiff:hostcomputer");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
-  value=GetImageProperty(image,"tiff:artist",exception);
+  value=GetImageArtifact(image,"tiff:artist");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
-  value=GetImageProperty(image,"tiff:timestamp",exception);
+  value=GetImageArtifact(image,"tiff:timestamp");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
-  value=GetImageProperty(image,"tiff:make",exception);
+  value=GetImageArtifact(image,"tiff:make");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
-  value=GetImageProperty(image,"tiff:model",exception);
+  value=GetImageArtifact(image,"tiff:model");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
-  value=GetImageProperty(image,"tiff:software",exception);
+  value=GetImageArtifact(image,"tiff:software");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
-  value=GetImageProperty(image,"tiff:copyright",exception);
+  value=GetImageArtifact(image,"tiff:copyright");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
-  value=GetImageProperty(image,"kodak-33423",exception);
+  value=GetImageArtifact(image,"kodak-33423");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,33423,value);
-  value=GetImageProperty(image,"kodak-36867",exception);
+  value=GetImageArtifact(image,"kodak-36867");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,36867,value);
-  value=GetImageProperty(image,"label",exception);
+  value=GetImageArtifact(image,"label");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
-  value=GetImageProperty(image,"comment",exception);
+  value=GetImageArtifact(image,"comment");
   if (value != (const char *) NULL)
     (void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
 }
@@ -2599,29 +2705,29 @@ static void TIFFSetEXIFProperties(TIFF *tiff,Image *image,
       case TIFF_SHORT:
       {
         uint16
-          shorty;
+          field;
 
-        shorty=(uint16) StringToLong(value);
-        (void) TIFFSetField(tiff,exif_info[i].tag,shorty);
+        field=(uint16) StringToLong(value);
+        (void) TIFFSetField(tiff,exif_info[i].tag,field);
         break;
       }
       case TIFF_LONG:
       {
         uint16
-          ssize_ty;
+          field;
 
-        ssize_ty=(uint16) StringToLong(value);
-        (void) TIFFSetField(tiff,exif_info[i].tag,ssize_ty);
+        field=(uint16) StringToLong(value);
+        (void) TIFFSetField(tiff,exif_info[i].tag,field);
         break;
       }
       case TIFF_RATIONAL:
       case TIFF_SRATIONAL:
       {
         float
-          rational;
+          field;
 
-        rational=StringToDouble(value,(char **) NULL);
-        (void) TIFFSetField(tiff,exif_info[i].tag,rational);
+        field=StringToDouble(value,(char **) NULL);
+        (void) TIFFSetField(tiff,exif_info[i].tag,field);
         break;
       }
       default:
@@ -2714,7 +2820,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
   error_handler=TIFFSetErrorHandler((TIFFErrorHandler) TIFFErrors);
   warning_handler=TIFFSetWarningHandler((TIFFErrorHandler) TIFFWarnings);
   endian_type=UndefinedEndian;
-  option=GetImageArtifact(image,"tiff:endian");
+  option=GetImageOption(image_info,"tiff:endian");
   if (option != (const char *) NULL)
     {
       if (LocaleNCompare(option,"msb",3) == 0)
@@ -2757,6 +2863,28 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     if ((image_info->type != UndefinedType) &&
         (image_info->type != OptimizeType))
       (void) SetImageType(image,image_info->type,exception);
+    compression=UndefinedCompression;
+    if (image->compression != JPEGCompression)
+      compression=image->compression;
+    if (image_info->compression != UndefinedCompression)
+      compression=image_info->compression;
+    switch (compression)
+    {
+      case FaxCompression:
+      case Group4Compression:
+      {
+        (void) SetImageType(image,BilevelType,exception);
+        break;
+      }
+      case JPEGCompression:
+      {
+        (void) SetImageStorageClass(image,DirectClass,exception);
+        (void) SetImageDepth(image,8,exception);
+        break;
+      }
+      default:
+        break;
+    }
     quantum_info=AcquireQuantumInfo(image_info,image);
     if (quantum_info == (QuantumInfo *) NULL)
       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
@@ -2776,9 +2904,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
     (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
     (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
-    compression=image->compression;
-    if (image_info->compression != UndefinedCompression)
-      compression=image_info->compression;
     switch (compression)
     {
       case FaxCompression:
@@ -2879,23 +3004,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         }
       }
 #endif
-    switch (compression)
-    {
-      case FaxCompression:
-      case Group4Compression:
-      {
-        (void) SetImageType(image,BilevelType,exception);
-        break;
-      }
-      case JPEGCompression:
-      {
-        (void) SetImageStorageClass(image,DirectClass,exception);
-        (void) SetImageDepth(image,8,exception);
-        break;
-      }
-      default:
-        break;
-    }
     if (image->colorspace == CMYKColorspace)
       {
         photometric=PHOTOMETRIC_SEPARATED;
@@ -2933,7 +3041,8 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                   MagickFalse ? PHOTOMETRIC_MINISWHITE :
                   PHOTOMETRIC_MINISBLACK);
                 (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
-                if ((image_info->depth == 0) && (image->alpha_trait != BlendPixelTrait) &&
+                if ((image_info->depth == 0) &&
+                    (image->alpha_trait != BlendPixelTrait) &&
                     (IsImageMonochrome(image,exception) != MagickFalse))
                   {
                     status=SetQuantumDepth(image,quantum_info,1);
@@ -2963,9 +3072,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
                 }
           }
       }
-    if ((photometric == PHOTOMETRIC_RGB) &&
-        (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
-      (void) TransformImageColorspace(image,sRGBColorspace,exception);
     switch (image->endian)
     {
       case LSBEndian:
@@ -2998,7 +3104,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
          compress_tag=COMPRESSION_NONE;
          endian=FILLORDER_MSB2LSB;
        }
-    option=GetImageArtifact(image,"tiff:fill-order");
+    option=GetImageOption(image_info,"tiff:fill-order");
     if (option != (const char *) NULL)
       {
         if (LocaleNCompare(option,"msb",3) == 0)
@@ -3021,7 +3127,7 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         */
         extra_samples=1;
         sample_info[0]=EXTRASAMPLE_UNASSALPHA;
-        option=GetImageArtifact(image,"tiff:alpha");
+        option=GetImageOption(image_info,"tiff:alpha");
         if ((option != (const char *) NULL) &&
             (LocaleCompare(option,"associated") == 0))
           sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
@@ -3062,11 +3168,8 @@ 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=1;
-    if (TIFFScanlineSize(tiff) != 0)
-      rows_per_strip=(uint32) MagickMax((size_t) TIFFDefaultStripSize(tiff,0),
-        1);
-    option=GetImageArtifact(image,"tiff:rows-per-strip");
+     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)
@@ -3084,8 +3187,6 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
           flags;
 
         rows_per_strip+=(16-(rows_per_strip % 16));
-        if (image->quality != 0)
-          (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image->quality);
         if (image_info->quality != UndefinedCompressionQuality)
           (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
         (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
@@ -3175,9 +3276,11 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       default:
         break;
     }
-    option=GetImageArtifact(image,"tiff:rows-per-strip");
-    if (option == (const char *) NULL)
-      (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
+    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
@@ -3194,13 +3297,22 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
         (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
         (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x);
         (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y);
-        if ((image->page.x != 0) || (image->page.y != 0))
+        if ((image->page.x < 0) || (image->page.y < 0))
+          (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
+            "TIFF: negative image positions unsupported","%s",image->filename);
+        if ((image->page.x > 0) && (image->resolution.x > 0.0))
           {
             /*
-              Set image position.
+              Set horizontal image position.
             */
             (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
               image->resolution.x);
+          }
+        if ((image->page.y > 0) && (image->resolution.y > 0.0))
+          {
+            /*
+              Set vertical image position.
+            */
             (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
               image->resolution.y);
           }
@@ -3248,7 +3360,9 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
       (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
     }
     (void) TIFFSetProperties(tiff,image,exception);
+DisableMSCWarning(4127)
     if (0)
+RestoreMSCWarning
       (void) TIFFSetEXIFProperties(tiff,image,exception);
     /*
       Write image scanlines.
@@ -3494,7 +3608,9 @@ static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
     if (image->colorspace == LabColorspace)
       DecodeLabImage(image,exception);
     DestroyTIFFInfo(&tiff_info);
-    if (0 && (image_info->verbose == MagickTrue))
+DisableMSCWarning(4127)
+    if (0 && (image_info->verbose != MagickFalse))
+RestoreMSCWarning
       TIFFPrintDirectory(tiff,stdout,MagickFalse);
     (void) TIFFWriteDirectory(tiff);
     image=SyncNextImageInList(image);