The Free Software Media System - Server Backend & API
use taglibsharp to read image sizes
Luke Pulverenti11d7585aa3bf
diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.csdeleted file mode 100644index 1c70b3bb6c..0000000000--- a/Emby.Drawing/Common/ImageHeader.cs+++ /dev/null@@ -1,223 +0,0 @@-using MediaBrowser.Common.IO;-using MediaBrowser.Model.Drawing;-using MediaBrowser.Model.Logging;-using System;-using System.Collections.Generic;-using System.IO;-using System.Linq;--namespace Emby.Drawing.Common-{- /// <summary>- /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349- /// http://www.codeproject.com/Articles/35978/Reading-Image-Headers-to-Get-Width-and-Height- /// Minor improvements including supporting unsigned 16-bit integers when decoding Jfif and added logic- /// to load the image using new Bitmap if reading the headers fails- /// </summary>- public static class ImageHeader- {- /// <summary>- /// The error message- /// </summary>- const string ErrorMessage = "Could not recognize image format.";-- /// <summary>- /// The image format decoders- /// </summary>- private static readonly KeyValuePair<byte[], Func<BinaryReader, ImageSize>>[] ImageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, ImageSize>>- {- { new byte[] { 0x42, 0x4D }, DecodeBitmap },- { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },- { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },- { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },- { new byte[] { 0xff, 0xd8 }, DecodeJfif }-- }.ToArray();-- private static readonly int MaxMagicBytesLength = ImageFormatDecoders.Select(i => i.Key.Length).OrderByDescending(i => i).First();-- /// <summary>- /// Gets the dimensions of an image.- /// </summary>- /// <param name="path">The path of the image to get the dimensions of.</param>- /// <param name="logger">The logger.</param>- /// <param name="fileSystem">The file system.</param>- /// <returns>The dimensions of the specified image.</returns>- /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>- public static ImageSize GetDimensions(string path, ILogger logger, IFileSystem fileSystem)- {- using (var fs = fileSystem.OpenRead(path))- {- using (var binaryReader = new BinaryReader(fs))- {- return GetDimensions(binaryReader);- }- }- }-- /// <summary>- /// Gets the dimensions of an image.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>Size.</returns>- /// <exception cref="System.ArgumentException">binaryReader</exception>- /// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>- private static ImageSize GetDimensions(BinaryReader binaryReader)- {- var magicBytes = new byte[MaxMagicBytesLength];-- for (var i = 0; i < MaxMagicBytesLength; i += 1)- {- magicBytes[i] = binaryReader.ReadByte();-- foreach (var kvPair in ImageFormatDecoders)- {- if (StartsWith(magicBytes, kvPair.Key))- {- return kvPair.Value(binaryReader);- }- }- }-- throw new ArgumentException(ErrorMessage, "binaryReader");- }-- /// <summary>- /// Startses the with.- /// </summary>- /// <param name="thisBytes">The this bytes.</param>- /// <param name="thatBytes">The that bytes.</param>- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>- private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)- {- for (int i = 0; i < thatBytes.Length; i += 1)- {- if (thisBytes[i] != thatBytes[i])- {- return false;- }- }-- return true;- }-- /// <summary>- /// Reads the little endian int16.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>System.Int16.</returns>- private static short ReadLittleEndianInt16(BinaryReader binaryReader)- {- var bytes = new byte[sizeof(short)];-- for (int i = 0; i < sizeof(short); i += 1)- {- bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();- }- return BitConverter.ToInt16(bytes, 0);- }-- /// <summary>- /// Reads the little endian int32.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>System.Int32.</returns>- private static int ReadLittleEndianInt32(BinaryReader binaryReader)- {- var bytes = new byte[sizeof(int)];- for (int i = 0; i < sizeof(int); i += 1)- {- bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();- }- return BitConverter.ToInt32(bytes, 0);- }-- /// <summary>- /// Decodes the bitmap.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>Size.</returns>- private static ImageSize DecodeBitmap(BinaryReader binaryReader)- {- binaryReader.ReadBytes(16);- int width = binaryReader.ReadInt32();- int height = binaryReader.ReadInt32();- return new ImageSize- {- Width = width,- Height = height- };- }-- /// <summary>- /// Decodes the GIF.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>Size.</returns>- private static ImageSize DecodeGif(BinaryReader binaryReader)- {- int width = binaryReader.ReadInt16();- int height = binaryReader.ReadInt16();- return new ImageSize- {- Width = width,- Height = height- };- }-- /// <summary>- /// Decodes the PNG.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>Size.</returns>- private static ImageSize DecodePng(BinaryReader binaryReader)- {- binaryReader.ReadBytes(8);- int width = ReadLittleEndianInt32(binaryReader);- int height = ReadLittleEndianInt32(binaryReader);- return new ImageSize- {- Width = width,- Height = height- };- }-- /// <summary>- /// Decodes the jfif.- /// </summary>- /// <param name="binaryReader">The binary reader.</param>- /// <returns>Size.</returns>- /// <exception cref="System.ArgumentException"></exception>- private static ImageSize DecodeJfif(BinaryReader binaryReader)- {- while (binaryReader.ReadByte() == 0xff)- {- byte marker = binaryReader.ReadByte();- short chunkLength = ReadLittleEndianInt16(binaryReader);- if (marker == 0xc0)- {- binaryReader.ReadByte();- int height = ReadLittleEndianInt16(binaryReader);- int width = ReadLittleEndianInt16(binaryReader);- return new ImageSize- {- Width = width,- Height = height- };- }-- if (chunkLength < 0)- {- var uchunkLength = (ushort)chunkLength;- binaryReader.ReadBytes(uchunkLength - 2);- }- else- {- binaryReader.ReadBytes(chunkLength - 2);- }- }-- throw new ArgumentException(ErrorMessage);- }- }-}diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csprojindex ab53f75500..cbc9966597 100644--- a/Emby.Drawing/Emby.Drawing.csproj+++ b/Emby.Drawing/Emby.Drawing.csproj@@ -36,6 +36,9 @@<SpecificVersion>False</SpecificVersion><HintPath>..\packages\ImageMagickSharp.1.0.0.16\lib\net45\ImageMagickSharp.dll</HintPath></Reference>+ <Reference Include="policy.2.0.taglib-sharp">+ <HintPath>..\packages\taglib.2.1.0.0\lib\policy.2.0.taglib-sharp.dll</HintPath>+ </Reference><Reference Include="System" /><Reference Include="System.Core" /><Reference Include="System.Drawing" />@@ -44,6 +47,9 @@<Reference Include="Microsoft.CSharp" /><Reference Include="System.Data" /><Reference Include="System.Xml" />+ <Reference Include="taglib-sharp">+ <HintPath>..\packages\taglib.2.1.0.0\lib\taglib-sharp.dll</HintPath>+ </Reference></ItemGroup><ItemGroup><Compile Include="..\SharedVersion.cs">@@ -56,7 +62,6 @@<Compile Include="GDI\PlayedIndicatorDrawer.cs" /><Compile Include="GDI\UnplayedCountIndicator.cs" /><Compile Include="IImageEncoder.cs" />- <Compile Include="Common\ImageHeader.cs" /><Compile Include="ImageHelpers.cs" /><Compile Include="ImageMagick\ImageMagickEncoder.cs" /><Compile Include="ImageMagick\StripCollageBuilder.cs" />diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.csindex d4fce76d02..3faa3e3e9a 100644--- a/Emby.Drawing/ImageProcessor.cs+++ b/Emby.Drawing/ImageProcessor.cs@@ -1,5 +1,4 @@-using Emby.Drawing.Common;-using MediaBrowser.Common.Extensions;+using MediaBrowser.Common.Extensions;using MediaBrowser.Common.IO;using MediaBrowser.Controller;using MediaBrowser.Controller.Drawing;@@ -399,6 +398,8 @@ namespace Emby.Drawing{size = GetImageSizeInternal(path, allowSlowMethod);+ StartSaveImageSizeTimer();+_cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size);}@@ -413,28 +414,18 @@ namespace Emby.Drawing/// <returns>ImageSize.</returns>private ImageSize GetImageSizeInternal(string path, bool allowSlowMethod){- ImageSize size;-- try+ using (var file = TagLib.File.Create(path)){- size = ImageHeader.GetDimensions(path, _logger, _fileSystem);- }- catch- {- if (!allowSlowMethod)- {- throw;- }- //_logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);-- CheckDisposed();+ var image = file as TagLib.Image.File;- size = _imageEncoder.GetImageSize(path);+ var properties = image.Properties;++ return new ImageSize+ {+ Height = properties.PhotoHeight,+ Width = properties.PhotoWidth+ };}-- StartSaveImageSizeTimer();-- return size;}private readonly Timer _saveImageSizeTimer;diff --git a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csprojindex e765b1ca37..eb1122902a 100644--- a/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj+++ b/MediaBrowser.Common.Implementations/MediaBrowser.Common.Implementations.csproj@@ -48,9 +48,9 @@<RunPostBuildEvent>Always</RunPostBuildEvent></PropertyGroup><ItemGroup>- <Reference Include="NLog, Version=4.1.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">+ <Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL"><SpecificVersion>False</SpecificVersion>- <HintPath>..\packages\NLog.4.1.0\lib\net45\NLog.dll</HintPath>+ <HintPath>..\packages\NLog.4.1.1\lib\net45\NLog.dll</HintPath></Reference><Reference Include="SharpCompress, Version=0.10.2.0, Culture=neutral, PublicKeyToken=beaf6f427e128133, processorArchitecture=MSIL"><SpecificVersion>False</SpecificVersion>diff --git a/MediaBrowser.Providers/Photos/PhotoProvider.cs b/MediaBrowser.Providers/Photos/PhotoProvider.csindex b635d4ead4..ef31449589 100644--- a/MediaBrowser.Providers/Photos/PhotoProvider.cs+++ b/MediaBrowser.Providers/Photos/PhotoProvider.cs@@ -31,110 +31,111 @@ namespace MediaBrowser.Providers.Photostry{- var file = File.Create(item.Path);-- var image = file as TagLib.Image.File;-- var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;-- if (tag != null)+ using (var file = TagLib.File.Create(item.Path)){- var structure = tag.Structure;+ var image = file as TagLib.Image.File;- if (structure != null)+ var tag = file.GetTag(TagTypes.TiffIFD) as IFDTag;++ if (tag != null){- var exif = structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) as SubIFDEntry;+ var structure = tag.Structure;- if (exif != null)+ if (structure != null){- var exifStructure = exif.Structure;+ var exif = structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) as SubIFDEntry;- if (exifStructure != null)+ if (exif != null){- var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;+ var exifStructure = exif.Structure;- if (entry != null)+ if (exifStructure != null){- double val = entry.Value.Numerator;- val /= entry.Value.Denominator;- item.Aperture = val;- }-- entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;-- if (entry != null)- {- double val = entry.Value.Numerator;- val /= entry.Value.Denominator;- item.ShutterSpeed = val;+ var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;++ if (entry != null)+ {+ double val = entry.Value.Numerator;+ val /= entry.Value.Denominator;+ item.Aperture = val;+ }++ entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;++ if (entry != null)+ {+ double val = entry.Value.Numerator;+ val /= entry.Value.Denominator;+ item.ShutterSpeed = val;+ }}}}}- }-- item.CameraMake = image.ImageTag.Make;- item.CameraModel = image.ImageTag.Model;- item.Width = image.Properties.PhotoWidth;- item.Height = image.Properties.PhotoHeight;+ item.CameraMake = image.ImageTag.Make;+ item.CameraModel = image.ImageTag.Model;- var rating = image.ImageTag.Rating;- if (rating.HasValue)- {- item.CommunityRating = rating;- }- else- {- item.CommunityRating = null;- }+ item.Width = image.Properties.PhotoWidth;+ item.Height = image.Properties.PhotoHeight;- item.Overview = image.ImageTag.Comment;+ var rating = image.ImageTag.Rating;+ if (rating.HasValue)+ {+ item.CommunityRating = rating;+ }+ else+ {+ item.CommunityRating = null;+ }- if (!string.IsNullOrWhiteSpace(image.ImageTag.Title))- {- item.Name = image.ImageTag.Title;- }+ item.Overview = image.ImageTag.Comment;- var dateTaken = image.ImageTag.DateTime;- if (dateTaken.HasValue)- {- item.DateCreated = dateTaken.Value;- item.PremiereDate = dateTaken.Value;- item.ProductionYear = dateTaken.Value.Year;- }+ if (!string.IsNullOrWhiteSpace(image.ImageTag.Title))+ {+ item.Name = image.ImageTag.Title;+ }- item.Genres = image.ImageTag.Genres.ToList();- item.Tags = image.ImageTag.Keywords.ToList();- item.Software = image.ImageTag.Software;+ var dateTaken = image.ImageTag.DateTime;+ if (dateTaken.HasValue)+ {+ item.DateCreated = dateTaken.Value;+ item.PremiereDate = dateTaken.Value;+ item.ProductionYear = dateTaken.Value.Year;+ }- if (image.ImageTag.Orientation == TagLib.Image.ImageOrientation.None)- {- item.Orientation = null;- }- else- {- Model.Drawing.ImageOrientation orientation;- if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out orientation))+ item.Genres = image.ImageTag.Genres.ToList();+ item.Tags = image.ImageTag.Keywords.ToList();+ item.Software = image.ImageTag.Software;++ if (image.ImageTag.Orientation == TagLib.Image.ImageOrientation.None){- item.Orientation = orientation;+ item.Orientation = null;+ }+ else+ {+ Model.Drawing.ImageOrientation orientation;+ if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out orientation))+ {+ item.Orientation = orientation;+ }}- }- item.ExposureTime = image.ImageTag.ExposureTime;- item.FocalLength = image.ImageTag.FocalLength;+ item.ExposureTime = image.ImageTag.ExposureTime;+ item.FocalLength = image.ImageTag.FocalLength;- item.Latitude = image.ImageTag.Latitude;- item.Longitude = image.ImageTag.Longitude;- item.Altitude = image.ImageTag.Altitude;+ item.Latitude = image.ImageTag.Latitude;+ item.Longitude = image.ImageTag.Longitude;+ item.Altitude = image.ImageTag.Altitude;- if (image.ImageTag.ISOSpeedRatings.HasValue)- {- item.IsoSpeedRating = Convert.ToInt32(image.ImageTag.ISOSpeedRatings.Value);- }- else- {- item.IsoSpeedRating = null;+ if (image.ImageTag.ISOSpeedRatings.HasValue)+ {+ item.IsoSpeedRating = Convert.ToInt32(image.ImageTag.ISOSpeedRatings.Value);+ }+ else+ {+ item.IsoSpeedRating = null;+ }}}catch (Exception e)