diff options
| author | Luke <luke.pulverenti@gmail.com> | 2015-04-14 00:43:41 -0400 |
|---|---|---|
| committer | Luke <luke.pulverenti@gmail.com> | 2015-04-14 00:43:41 -0400 |
| commit | 935de313d58c7a7ba792345c16cfd1c1aad09a78 (patch) | |
| tree | 2e9334986de5864b00d4901f031b5de6a970305e /Emby.Drawing | |
| parent | 71a4f2761e784513ae2f3dda03aa549903808ebb (diff) | |
| parent | bd253399c2f1913c544c93fd6927dee37f8add2f (diff) | |
Merge pull request #1079 from MediaBrowser/dev
3.0.5582.0
Diffstat (limited to 'Emby.Drawing')
| -rw-r--r-- | Emby.Drawing/Common/ImageHeader.cs | 223 | ||||
| -rw-r--r-- | Emby.Drawing/Emby.Drawing.csproj | 98 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/DynamicImageHelpers.cs | 138 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/GDIImageEncoder.cs | 254 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/ImageExtensions.cs | 217 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/PercentPlayedDrawer.cs | 34 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/PlayedIndicatorDrawer.cs | 32 | ||||
| -rw-r--r-- | Emby.Drawing/GDI/UnplayedCountIndicator.cs | 50 | ||||
| -rw-r--r-- | Emby.Drawing/IImageEncoder.cs | 53 | ||||
| -rw-r--r-- | Emby.Drawing/ImageMagick/ImageMagickEncoder.cs | 229 | ||||
| -rw-r--r-- | Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs | 40 | ||||
| -rw-r--r-- | Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs | 86 | ||||
| -rw-r--r-- | Emby.Drawing/ImageMagick/StripCollageBuilder.cs | 518 | ||||
| -rw-r--r-- | Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs | 70 | ||||
| -rw-r--r-- | Emby.Drawing/ImageProcessor.cs | 768 | ||||
| -rw-r--r-- | Emby.Drawing/Properties/AssemblyInfo.cs | 31 | ||||
| -rw-r--r-- | Emby.Drawing/packages.config | 4 |
17 files changed, 2845 insertions, 0 deletions
diff --git a/Emby.Drawing/Common/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs new file mode 100644 index 0000000000..b66bd71ea5 --- /dev/null +++ b/Emby.Drawing/Common/ImageHeader.cs @@ -0,0 +1,223 @@ +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 = File.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.csproj new file mode 100644 index 0000000000..dbb976f036 --- /dev/null +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{08FFF49B-F175-4807-A2B5-73B0EBD9F716}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>Emby.Drawing</RootNamespace> + <AssemblyName>Emby.Drawing</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir> + <RestorePackages>true</RestorePackages> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="ImageMagickSharp, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\ImageMagickSharp.1.0.0.14\lib\net45\ImageMagickSharp.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Drawing" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="..\SharedVersion.cs"> + <Link>Properties\SharedVersion.cs</Link> + </Compile> + <Compile Include="GDI\DynamicImageHelpers.cs" /> + <Compile Include="GDI\GDIImageEncoder.cs" /> + <Compile Include="GDI\ImageExtensions.cs" /> + <Compile Include="GDI\PercentPlayedDrawer.cs" /> + <Compile Include="GDI\PlayedIndicatorDrawer.cs" /> + <Compile Include="GDI\UnplayedCountIndicator.cs" /> + <Compile Include="IImageEncoder.cs" /> + <Compile Include="Common\ImageHeader.cs" /> + <Compile Include="ImageMagick\ImageMagickEncoder.cs" /> + <Compile Include="ImageMagick\StripCollageBuilder.cs" /> + <Compile Include="ImageProcessor.cs" /> + <Compile Include="ImageMagick\PercentPlayedDrawer.cs" /> + <Compile Include="ImageMagick\PlayedIndicatorDrawer.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="ImageMagick\UnplayedCountIndicator.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="ImageMagick\fonts\MontserratLight.otf" /> + <EmbeddedResource Include="ImageMagick\fonts\robotoregular.ttf" /> + <EmbeddedResource Include="ImageMagick\fonts\webdings.ttf" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj"> + <Project>{9142eefa-7570-41e1-bfcc-468bb571af2f}</Project> + <Name>MediaBrowser.Common</Name> + </ProjectReference> + <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj"> + <Project>{17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2}</Project> + <Name>MediaBrowser.Controller</Name> + </ProjectReference> + <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj"> + <Project>{7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}</Project> + <Name>MediaBrowser.Model</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project>
\ No newline at end of file diff --git a/Emby.Drawing/GDI/DynamicImageHelpers.cs b/Emby.Drawing/GDI/DynamicImageHelpers.cs new file mode 100644 index 0000000000..c49007c5fd --- /dev/null +++ b/Emby.Drawing/GDI/DynamicImageHelpers.cs @@ -0,0 +1,138 @@ +using Emby.Drawing.ImageMagick; +using MediaBrowser.Common.IO; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; + +namespace Emby.Drawing.GDI +{ + public static class DynamicImageHelpers + { + public static void CreateThumbCollage(List<string> files, + IFileSystem fileSystem, + string file, + int width, + int height) + { + const int numStrips = 4; + files = StripCollageBuilder.ProjectPaths(files, numStrips).ToList(); + + const int rows = 1; + int cols = numStrips; + + int cellWidth = 2 * (width / 3); + int cellHeight = height; + var index = 0; + + using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb)) + { + using (var graphics = Graphics.FromImage(img)) + { + graphics.CompositingQuality = CompositingQuality.HighQuality; + graphics.SmoothingMode = SmoothingMode.HighQuality; + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + graphics.CompositingMode = CompositingMode.SourceCopy; + + for (var row = 0; row < rows; row++) + { + for (var col = 0; col < cols; col++) + { + var x = col * (cellWidth / 2); + var y = row * cellHeight; + + if (files.Count > index) + { + using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true)) + { + using (var memoryStream = new MemoryStream()) + { + fileStream.CopyTo(memoryStream); + + memoryStream.Position = 0; + + using (var imgtemp = Image.FromStream(memoryStream, true, false)) + { + graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight); + } + } + } + } + + index++; + } + } + img.Save(file); + } + } + } + + public static void CreateSquareCollage(List<string> files, + IFileSystem fileSystem, + string file, + int width, + int height) + { + files = StripCollageBuilder.ProjectPaths(files, 4).ToList(); + + const int rows = 2; + const int cols = 2; + + int singleSize = width / 2; + var index = 0; + + using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb)) + { + using (var graphics = Graphics.FromImage(img)) + { + graphics.CompositingQuality = CompositingQuality.HighQuality; + graphics.SmoothingMode = SmoothingMode.HighQuality; + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + graphics.CompositingMode = CompositingMode.SourceCopy; + + for (var row = 0; row < rows; row++) + { + for (var col = 0; col < cols; col++) + { + var x = col * singleSize; + var y = row * singleSize; + + using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true)) + { + using (var memoryStream = new MemoryStream()) + { + fileStream.CopyTo(memoryStream); + + memoryStream.Position = 0; + + using (var imgtemp = Image.FromStream(memoryStream, true, false)) + { + graphics.DrawImage(imgtemp, x, y, singleSize, singleSize); + } + } + } + + index++; + } + } + img.Save(file); + } + } + } + + private static Stream GetStream(Image image) + { + var ms = new MemoryStream(); + + image.Save(ms, ImageFormat.Png); + + ms.Position = 0; + + return ms; + } + } +} diff --git a/Emby.Drawing/GDI/GDIImageEncoder.cs b/Emby.Drawing/GDI/GDIImageEncoder.cs new file mode 100644 index 0000000000..d968b8b5fe --- /dev/null +++ b/Emby.Drawing/GDI/GDIImageEncoder.cs @@ -0,0 +1,254 @@ +using MediaBrowser.Common.IO; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Logging; +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat; + +namespace Emby.Drawing.GDI +{ + public class GDIImageEncoder : IImageEncoder + { + private readonly IFileSystem _fileSystem; + private readonly ILogger _logger; + + public GDIImageEncoder(IFileSystem fileSystem, ILogger logger) + { + _fileSystem = fileSystem; + _logger = logger; + } + + public string[] SupportedInputFormats + { + get + { + return new[] + { + "png", + "jpeg", + "jpg", + "gif", + "bmp" + }; + } + } + + public ImageFormat[] SupportedOutputFormats + { + get + { + return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; + } + } + + public ImageSize GetImageSize(string path) + { + using (var image = Image.FromFile(path)) + { + return new ImageSize + { + Width = image.Width, + Height = image.Height + }; + } + } + + public void CropWhiteSpace(string inputPath, string outputPath) + { + using (var image = (Bitmap)Image.FromFile(inputPath)) + { + using (var croppedImage = image.CropWhitespace()) + { + Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + + using (var outputStream = _fileSystem.GetFileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read, false)) + { + croppedImage.Save(System.Drawing.Imaging.ImageFormat.Png, outputStream, 100); + } + } + } + } + + public void EncodeImage(string inputPath, string cacheFilePath, int width, int height, int quality, ImageProcessingOptions options) + { + var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed > 0; + + using (var originalImage = Image.FromFile(inputPath)) + { + var newWidth = Convert.ToInt32(width); + var newHeight = Convert.ToInt32(height); + + var selectedOutputFormat = options.OutputFormat; + + // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here + // Also, Webp only supports Format32bppArgb and Format32bppRgb + var pixelFormat = selectedOutputFormat == ImageFormat.Webp + ? PixelFormat.Format32bppArgb + : PixelFormat.Format32bppPArgb; + + using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat)) + { + // Mono throw an exeception if assign 0 to SetResolution + if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0) + { + // Preserve the original resolution + thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution); + } + + using (var thumbnailGraph = Graphics.FromImage(thumbnail)) + { + thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; + thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; + thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; + thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; + thumbnailGraph.CompositingMode = !hasPostProcessing ? + CompositingMode.SourceCopy : + CompositingMode.SourceOver; + + SetBackgroundColor(thumbnailGraph, options); + + thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight); + + DrawIndicator(thumbnailGraph, newWidth, newHeight, options); + + var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat); + + Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); + + // Save to the cache location + using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false)) + { + // Save to the memory stream + thumbnail.Save(outputFormat, cacheFileStream, quality); + } + } + } + + } + } + + /// <summary> + /// Sets the color of the background. + /// </summary> + /// <param name="graphics">The graphics.</param> + /// <param name="options">The options.</param> + private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options) + { + var color = options.BackgroundColor; + + if (!string.IsNullOrEmpty(color)) + { + Color drawingColor; + + try + { + drawingColor = ColorTranslator.FromHtml(color); + } + catch + { + drawingColor = ColorTranslator.FromHtml("#" + color); + } + + graphics.Clear(drawingColor); + } + } + + /// <summary> + /// Draws the indicator. + /// </summary> + /// <param name="graphics">The graphics.</param> + /// <param name="imageWidth">Width of the image.</param> + /// <param name="imageHeight">Height of the image.</param> + /// <param name="options">The options.</param> + private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options) + { + if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0)) + { + return; + } + + try + { + if (options.AddPlayedIndicator) + { + var currentImageSize = new Size(imageWidth, imageHeight); + + new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize); + } + else if (options.UnplayedCount.HasValue) + { + var currentImageSize = new Size(imageWidth, imageHeight); + + new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value); + } + + if (options.PercentPlayed > 0) + { + var currentImageSize = new Size(imageWidth, imageHeight); + + new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed); + } + } + catch (Exception ex) + { + _logger.ErrorException("Error drawing indicator overlay", ex); + } + } + + /// <summary> + /// Gets the output format. + /// </summary> + /// <param name="image">The image.</param> + /// <param name="outputFormat">The output format.</param> + /// <returns>ImageFormat.</returns> + private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat) + { + switch (outputFormat) + { + case ImageFormat.Bmp: + return System.Drawing.Imaging.ImageFormat.Bmp; + case ImageFormat.Gif: + return System.Drawing.Imaging.ImageFormat.Gif; + case ImageFormat.Jpg: + return System.Drawing.Imaging.ImageFormat.Jpeg; + case ImageFormat.Png: + return System.Drawing.Imaging.ImageFormat.Png; + default: + return image.RawFormat; + } + } + + public void CreateImageCollage(ImageCollageOptions options) + { + double ratio = options.Width; + ratio /= options.Height; + + if (ratio >= 1.4) + { + DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height); + } + else if (ratio >= .9) + { + DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height); + } + else + { + DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width); + } + } + + public void Dispose() + { + } + + public string Name + { + get { return "GDI"; } + } + } +} diff --git a/Emby.Drawing/GDI/ImageExtensions.cs b/Emby.Drawing/GDI/ImageExtensions.cs new file mode 100644 index 0000000000..6af5a8688f --- /dev/null +++ b/Emby.Drawing/GDI/ImageExtensions.cs @@ -0,0 +1,217 @@ +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; + +namespace Emby.Drawing.GDI +{ + public static class ImageExtensions + { + /// <summary> + /// Saves the image. + /// </summary> + /// <param name="outputFormat">The output format.</param> + /// <param name="image">The image.</param> + /// <param name="toStream">To stream.</param> + /// <param name="quality">The quality.</param> + public static void Save(this Image image, ImageFormat outputFormat, Stream toStream, int quality) + { + // Use special save methods for jpeg and png that will result in a much higher quality image + // All other formats use the generic Image.Save + if (ImageFormat.Jpeg.Equals(outputFormat)) + { + SaveAsJpeg(image, toStream, quality); + } + else if (ImageFormat.Png.Equals(outputFormat)) + { + image.Save(toStream, ImageFormat.Png); + } + else + { + image.Save(toStream, outputFormat); + } + } + + /// <summary> + /// Saves the JPEG. + /// </summary> + /// <param name="image">The image.</param> + /// <param name="target">The target.</param> + /// <param name="quality">The quality.</param> + public static void SaveAsJpeg(this Image image, Stream target, int quality) + { + using (var encoderParameters = new EncoderParameters(1)) + { + encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality); + image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters); + } + } + + private static readonly ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders(); + + /// <summary> + /// Gets the image codec info. + /// </summary> + /// <param name="mimeType">Type of the MIME.</param> + /// <returns>ImageCodecInfo.</returns> + private static ImageCodecInfo GetImageCodecInfo(string mimeType) + { + foreach (var encoder in Encoders) + { + if (string.Equals(encoder.MimeType, mimeType, StringComparison.OrdinalIgnoreCase)) + { + return encoder; + } + } + + return Encoders.Length == 0 ? null : Encoders[0]; + } + + /// <summary> + /// Crops an image by removing whitespace and transparency from the edges + /// </summary> + /// <param name="bmp">The BMP.</param> + /// <returns>Bitmap.</returns> + /// <exception cref="System.Exception"></exception> + public static Bitmap CropWhitespace(this Bitmap bmp) + { + var width = bmp.Width; + var height = bmp.Height; + + var topmost = 0; + for (int row = 0; row < height; ++row) + { + if (IsAllWhiteRow(bmp, row, width)) + topmost = row; + else break; + } + + int bottommost = 0; + for (int row = height - 1; row >= 0; --row) + { + if (IsAllWhiteRow(bmp, row, width)) + bottommost = row; + else break; + } + + int leftmost = 0, rightmost = 0; + for (int col = 0; col < width; ++col) + { + if (IsAllWhiteColumn(bmp, col, height)) + leftmost = col; + else + break; + } + + for (int col = width - 1; col >= 0; --col) + { + if (IsAllWhiteColumn(bmp, col, height)) + rightmost = col; + else + break; + } + + if (rightmost == 0) rightmost = width; // As reached left + if (bottommost == 0) bottommost = height; // As reached top. + + var croppedWidth = rightmost - leftmost; + var croppedHeight = bottommost - topmost; + + if (croppedWidth == 0) // No border on left or right + { + leftmost = 0; + croppedWidth = width; + } + + if (croppedHeight == 0) // No border on top or bottom + { + topmost = 0; + croppedHeight = height; + } + + // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here + var thumbnail = new Bitmap(croppedWidth, croppedHeight, PixelFormat.Format32bppPArgb); + + // Preserve the original resolution + TrySetResolution(thumbnail, bmp.HorizontalResolution, bmp.VerticalResolution); + + using (var thumbnailGraph = Graphics.FromImage(thumbnail)) + { + thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality; + thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; + thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; + thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; + thumbnailGraph.CompositingMode = CompositingMode.SourceCopy; + + thumbnailGraph.DrawImage(bmp, + new RectangleF(0, 0, croppedWidth, croppedHeight), + new RectangleF(leftmost, topmost, croppedWidth, croppedHeight), + GraphicsUnit.Pixel); + } + return thumbnail; + } + + /// <summary> + /// Tries the set resolution. + /// </summary> + /// <param name="bmp">The BMP.</param> + /// <param name="x">The x.</param> + /// <param name="y">The y.</param> + private static void TrySetResolution(Bitmap bmp, float x, float y) + { + if (x > 0 && y > 0) + { + bmp.SetResolution(x, y); + } + } + + /// <summary> + /// Determines whether or not a row of pixels is all whitespace + /// </summary> + /// <param name="bmp">The BMP.</param> + /// <param name="row">The row.</param> + /// <param name="width">The width.</param> + /// <returns><c>true</c> if [is all white row] [the specified BMP]; otherwise, <c>false</c>.</returns> + private static bool IsAllWhiteRow(Bitmap bmp, int row, int width) + { + for (var i = 0; i < width; ++i) + { + if (!IsWhiteSpace(bmp.GetPixel(i, row))) + { + return false; + } + } + return true; + } + + /// <summary> + /// Determines whether or not a column of pixels is all whitespace + /// </summary> + /// <param name="bmp">The BMP.</param> + /// <param name="col">The col.</param> + /// <param name="height">The height.</param> + /// <returns><c>true</c> if [is all white column] [the specified BMP]; otherwise, <c>false</c>.</returns> + private static bool IsAllWhiteColumn(Bitmap bmp, int col, int height) + { + for (var i = 0; i < height; ++i) + { + if (!IsWhiteSpace(bmp.GetPixel(col, i))) + { + return false; + } + } + return true; + } + + /// <summary> + /// Determines if a color is whitespace + /// </summary> + /// <param name="color">The color.</param> + /// <returns><c>true</c> if [is white space] [the specified color]; otherwise, <c>false</c>.</returns> + private static bool IsWhiteSpace(Color color) + { + return (color.R == 255 && color.G == 255 && color.B == 255) || color.A == 0; + } + } +} diff --git a/Emby.Drawing/GDI/PercentPlayedDrawer.cs b/Emby.Drawing/GDI/PercentPlayedDrawer.cs new file mode 100644 index 0000000000..c7afda60e4 --- /dev/null +++ b/Emby.Drawing/GDI/PercentPlayedDrawer.cs @@ -0,0 +1,34 @@ +using System; +using System.Drawing; + +namespace Emby.Drawing.GDI +{ + public class PercentPlayedDrawer + { + private const int IndicatorHeight = 8; + + public void Process(Graphics graphics, Size imageSize, double percent) + { + var y = imageSize.Height - IndicatorHeight; + + using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 0, 0, 0))) + { + const int innerX = 0; + var innerY = y; + var innerWidth = imageSize.Width; + var innerHeight = imageSize.Height; + + graphics.FillRectangle(backdroundBrush, innerX, innerY, innerWidth, innerHeight); + + using (var foregroundBrush = new SolidBrush(Color.FromArgb(82, 181, 75))) + { + double foregroundWidth = innerWidth; + foregroundWidth *= percent; + foregroundWidth /= 100; + + graphics.FillRectangle(foregroundBrush, innerX, innerY, Convert.ToInt32(Math.Round(foregroundWidth)), innerHeight); + } + } + } + } +} diff --git a/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs b/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs new file mode 100644 index 0000000000..4428e4cbac --- /dev/null +++ b/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs @@ -0,0 +1,32 @@ +using System.Drawing; + +namespace Emby.Drawing.GDI +{ + public class PlayedIndicatorDrawer + { + private const int IndicatorHeight = 40; + public const int IndicatorWidth = 40; + private const int FontSize = 40; + private const int OffsetFromTopRightCorner = 10; + + public void DrawPlayedIndicator(Graphics graphics, Size imageSize) + { + var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; + + using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75))) + { + graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight); + + x = imageSize.Width - 45 - OffsetFromTopRightCorner; + + using (var font = new Font("Webdings", FontSize, FontStyle.Regular, GraphicsUnit.Pixel)) + { + using (var fontBrush = new SolidBrush(Color.White)) + { + graphics.DrawString("a", font, fontBrush, x, OffsetFromTopRightCorner - 2); + } + } + } + } + } +} diff --git a/Emby.Drawing/GDI/UnplayedCountIndicator.cs b/Emby.Drawing/GDI/UnplayedCountIndicator.cs new file mode 100644 index 0000000000..6420abb27f --- /dev/null +++ b/Emby.Drawing/GDI/UnplayedCountIndicator.cs @@ -0,0 +1,50 @@ +using System.Drawing; + +namespace Emby.Drawing.GDI +{ + public class UnplayedCountIndicator + { + private const int IndicatorHeight = 41; + public const int IndicatorWidth = 41; + private const int OffsetFromTopRightCorner = 10; + + public void DrawUnplayedCountIndicator(Graphics graphics, Size imageSize, int count) + { + var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; + + using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75))) + { + graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight); + + var text = count.ToString(); + + x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner; + var y = OffsetFromTopRightCorner + 6; + var fontSize = 24; + + if (text.Length == 1) + { + x += 10; + } + else if (text.Length == 2) + { + x += 3; + } + else if (text.Length == 3) + { + x += 1; + y += 1; + fontSize = 20; + } + + using (var font = new Font("Sans-Serif", fontSize, FontStyle.Regular, GraphicsUnit.Pixel)) + { + using (var fontBrush = new SolidBrush(Color.White)) + { + graphics.DrawString(text, font, fontBrush, x, y); + } + } + } + } + } +} diff --git a/Emby.Drawing/IImageEncoder.cs b/Emby.Drawing/IImageEncoder.cs new file mode 100644 index 0000000000..29261dbdb3 --- /dev/null +++ b/Emby.Drawing/IImageEncoder.cs @@ -0,0 +1,53 @@ +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Drawing; +using System; + +namespace Emby.Drawing +{ + public interface IImageEncoder : IDisposable + { + /// <summary> + /// Gets the supported input formats. + /// </summary> + /// <value>The supported input formats.</value> + string[] SupportedInputFormats { get; } + /// <summary> + /// Gets the supported output formats. + /// </summary> + /// <value>The supported output formats.</value> + ImageFormat[] SupportedOutputFormats { get; } + /// <summary> + /// Gets the size of the image. + /// </summary> + /// <param name="path">The path.</param> + /// <returns>ImageSize.</returns> + ImageSize GetImageSize(string path); + /// <summary> + /// Crops the white space. + /// </summary> + /// <param name="inputPath">The input path.</param> + /// <param name="outputPath">The output path.</param> + void CropWhiteSpace(string inputPath, string outputPath); + /// <summary> + /// Encodes the image. + /// </summary> + /// <param name="inputPath">The input path.</param> + /// <param name="outputPath">The output path.</param> + /// <param name="width">The width.</param> + /// <param name="height">The height.</param> + /// <param name="quality">The quality.</param> + /// <param name="options">The options.</param> + void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options); + + /// <summary> + /// Creates the image collage. + /// </summary> + /// <param name="options">The options.</param> + void CreateImageCollage(ImageCollageOptions options); + /// <summary> + /// Gets the name. + /// </summary> + /// <value>The name.</value> + string Name { get; } + } +} diff --git a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs new file mode 100644 index 0000000000..3d6cdd03dd --- /dev/null +++ b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs @@ -0,0 +1,229 @@ +using ImageMagickSharp; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Logging; +using System; +using System.IO; + +namespace Emby.Drawing.ImageMagick +{ + public class ImageMagickEncoder : IImageEncoder + { + private readonly ILogger _logger; + private readonly IApplicationPaths _appPaths; + + public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths) + { + _logger = logger; + _appPaths = appPaths; + + LogImageMagickVersion(); + } + + public string[] SupportedInputFormats + { + get + { + // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif. + return new[] + { + "tiff", + "jpeg", + "jpg", + "png", + "aiff", + "cr2", + "crw", + "dng", + "nef", + "orf", + "pef", + "arw", + "webp", + "gif", + "bmp" + }; + } + } + + public ImageFormat[] SupportedOutputFormats + { + get + { + if (_webpAvailable) + { + return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; + } + return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png }; + } + } + + private void LogImageMagickVersion() + { + _logger.Info("ImageMagick version: " + Wand.VersionString); + TestWebp(); + } + + private bool _webpAvailable = true; + private void TestWebp() + { + try + { + var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp"); + Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); + + using (var wand = new MagickWand(1, 1, new PixelWand("none", 1))) + { + wand.SaveImage(tmpPath); + } + } + catch (Exception ex) + { + _logger.ErrorException("Error loading webp: ", ex); + _webpAvailable = false; + } + } + + public void CropWhiteSpace(string inputPath, string outputPath) + { + CheckDisposed(); + + using (var wand = new MagickWand(inputPath)) + { + wand.CurrentImage.TrimImage(10); + wand.SaveImage(outputPath); + } + } + + public ImageSize GetImageSize(string path) + { + CheckDisposed(); + + using (var wand = new MagickWand()) + { + wand.PingImage(path); + var img = wand.CurrentImage; + + return new ImageSize + { + Width = img.Width, + Height = img.Height + }; + } + } + + public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options) + { + if (string.IsNullOrWhiteSpace(options.BackgroundColor)) + { + using (var originalImage = new MagickWand(inputPath)) + { + originalImage.CurrentImage.ResizeImage(width, height); + + DrawIndicator(originalImage, width, height, options); + + originalImage.CurrentImage.CompressionQuality = quality; + + originalImage.SaveImage(outputPath); + } + } + else + { + using (var wand = new MagickWand(width, height, options.BackgroundColor)) + { + using (var originalImage = new MagickWand(inputPath)) + { + originalImage.CurrentImage.ResizeImage(width, height); + + wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0); + DrawIndicator(wand, width, height, options); + + wand.CurrentImage.CompressionQuality = quality; + + wand.SaveImage(outputPath); + } + } + } + } + + /// <summary> + /// Draws the indicator. + /// </summary> + /// <param name="wand">The wand.</param> + /// <param name="imageWidth">Width of the image.</param> + /// <param name="imageHeight">Height of the image.</param> + /// <param name="options">The options.</param> + private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options) + { + if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0)) + { + return; + } + + try + { + if (options.AddPlayedIndicator) + { + var currentImageSize = new ImageSize(imageWidth, imageHeight); + + new PlayedIndicatorDrawer(_appPaths).DrawPlayedIndicator(wand, currentImageSize); + } + else if (options.UnplayedCount.HasValue) + { + var currentImageSize = new ImageSize(imageWidth, imageHeight); + + new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value); + } + + if (options.PercentPlayed > 0) + { + new PercentPlayedDrawer().Process(wand, options.PercentPlayed); + } + } + catch (Exception ex) + { + _logger.ErrorException("Error drawing indicator overlay", ex); + } + } + + public void CreateImageCollage(ImageCollageOptions options) + { + double ratio = options.Width; + ratio /= options.Height; + + if (ratio >= 1.4) + { + new StripCollageBuilder(_appPaths).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text); + } + else if (ratio >= .9) + { + new StripCollageBuilder(_appPaths).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text); + } + else + { + new StripCollageBuilder(_appPaths).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text); + } + } + + public string Name + { + get { return "ImageMagick"; } + } + + private bool _disposed; + public void Dispose() + { + _disposed = true; + Wand.CloseEnvironment(); + } + + private void CheckDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(GetType().Name); + } + } + } +} diff --git a/Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs b/Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs new file mode 100644 index 0000000000..90f9d56095 --- /dev/null +++ b/Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs @@ -0,0 +1,40 @@ +using ImageMagickSharp; +using System; + +namespace Emby.Drawing.ImageMagick +{ + public class PercentPlayedDrawer + { + private const int IndicatorHeight = 8; + + public void Process(MagickWand wand, double percent) + { + var currentImage = wand.CurrentImage; + var height = currentImage.Height; + + using (var draw = new DrawingWand()) + { + using (PixelWand pixel = new PixelWand()) + { + var endX = currentImage.Width - 1; + var endY = height - 1; + + pixel.Color = "black"; + pixel.Opacity = 0.4; + draw.FillColor = pixel; + draw.DrawRectangle(0, endY - IndicatorHeight, endX, endY); + + double foregroundWidth = endX; + foregroundWidth *= percent; + foregroundWidth /= 100; + + pixel.Color = "#52B54B"; + pixel.Opacity = 0; + draw.FillColor = pixel; + draw.DrawRectangle(0, endY - IndicatorHeight, Convert.ToInt32(Math.Round(foregroundWidth)), endY); + wand.CurrentImage.DrawImage(draw); + } + } + } + } +} diff --git a/Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs b/Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs new file mode 100644 index 0000000000..5eeb157715 --- /dev/null +++ b/Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs @@ -0,0 +1,86 @@ +using ImageMagickSharp; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Drawing; +using System; +using System.IO; + +namespace Emby.Drawing.ImageMagick +{ + public class PlayedIndicatorDrawer + { + private const int FontSize = 52; + private const int OffsetFromTopRightCorner = 38; + + private readonly IApplicationPaths _appPaths; + + public PlayedIndicatorDrawer(IApplicationPaths appPaths) + { + _appPaths = appPaths; + } + + public void DrawPlayedIndicator(MagickWand wand, ImageSize imageSize) + { + var x = imageSize.Width - OffsetFromTopRightCorner; + + using (var draw = new DrawingWand()) + { + using (PixelWand pixel = new PixelWand()) + { + pixel.Color = "#52B54B"; + pixel.Opacity = 0.2; + draw.FillColor = pixel; + draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20); + + pixel.Opacity = 0; + pixel.Color = "white"; + draw.FillColor = pixel; + draw.Font = ExtractFont("webdings.ttf", _appPaths); + draw.FontSize = FontSize; + draw.FontStyle = FontStyleType.NormalStyle; + draw.TextAlignment = TextAlignType.CenterAlign; + draw.FontWeight = FontWeightType.RegularStyle; + draw.TextAntialias = true; + draw.DrawAnnotation(x + 4, OffsetFromTopRightCorner + 14, "a"); + + draw.FillColor = pixel; + wand.CurrentImage.DrawImage(draw); + } + } + } + + internal static string ExtractFont(string name, IApplicationPaths paths) + { + var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name); + + if (File.Exists(filePath)) + { + return filePath; + } + + var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name; + var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf"); + Directory.CreateDirectory(Path.GetDirectoryName(tempPath)); + + using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath)) + { + using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read)) + { + stream.CopyTo(fileStream); + } + } + + Directory.CreateDirectory(Path.GetDirectoryName(filePath)); + + try + { + File.Copy(tempPath, filePath, false); + } + catch (IOException) + { + + } + + return tempPath; + } + } +} diff --git a/Emby.Drawing/ImageMagick/StripCollageBuilder.cs b/Emby.Drawing/ImageMagick/StripCollageBuilder.cs new file mode 100644 index 0000000000..7cdd0077de --- /dev/null +++ b/Emby.Drawing/ImageMagick/StripCollageBuilder.cs @@ -0,0 +1,518 @@ +using ImageMagickSharp; +using MediaBrowser.Common.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Emby.Drawing.ImageMagick +{ + public class StripCollageBuilder + { + private readonly IApplicationPaths _appPaths; + + public StripCollageBuilder(IApplicationPaths appPaths) + { + _appPaths = appPaths; + } + + public void BuildPosterCollage(IEnumerable<string> paths, string outputPath, int width, int height, string text) + { + if (!string.IsNullOrWhiteSpace(text)) + { + using (var wand = BuildPosterCollageWandWithText(paths, text, width, height)) + { + wand.SaveImage(outputPath); + } + } + else + { + using (var wand = BuildPosterCollageWand(paths, width, height)) + { + wand.SaveImage(outputPath); + } + } + } + + public void BuildSquareCollage(IEnumerable<string> paths, string outputPath, int width, int height, string text) + { + if (!string.IsNullOrWhiteSpace(text)) + { + using (var wand = BuildSquareCollageWandWithText(paths, text, width, height)) + { + wand.SaveImage(outputPath); + } + } + else + { + using (var wand = BuildSquareCollageWand(paths, width, height)) + { + wand.SaveImage(outputPath); + } + } + } + + public void BuildThumbCollage(IEnumerable<string> paths, string outputPath, int width, int height, string text) + { + if (!string.IsNullOrWhiteSpace(text)) + { + using (var wand = BuildThumbCollageWandWithText(paths, text, width, height)) + { + wand.SaveImage(outputPath); + } + } + else + { + using (var wand = BuildThumbCollageWand(paths, width, height)) + { + wand.SaveImage(outputPath); + } + } + } + + internal static string[] ProjectPaths(IEnumerable<string> paths, int count) + { + var clone = paths.ToList(); + var list = new List<string>(); + + while (list.Count < count) + { + foreach (var path in clone) + { + list.Add(path); + + if (list.Count >= count) + { + break; + } + } + } + + return list.Take(count).ToArray(); + } + + private MagickWand BuildThumbCollageWandWithText(IEnumerable<string> paths, string text, int width, int height) + { + var inputPaths = ProjectPaths(paths, 8); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + using (var fcolor = new PixelWand(ColorName.White)) + { + draw.FillColor = fcolor; + draw.Font = MontserratLightFont; + draw.FontSize = 60; + draw.FontWeight = FontWeightType.LightStyle; + draw.TextAntialias = true; + } + + var fontMetrics = wand.QueryFontMetrics(draw, text); + var textContainerY = Convert.ToInt32(height * .165); + wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, text); + + var iSlice = Convert.ToInt32(width * .1166666667); + int iTrans = Convert.ToInt32(height * 0.2); + int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296); + var horizontalImagePadding = Convert.ToInt32(width * 0.0125); + + foreach (var element in wandImages.ImageList) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = new PixelWand("none", 1); + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852)); + } + } + } + } + } + } + + return wand; + } + } + + private MagickWand BuildPosterCollageWand(IEnumerable<string> paths, int width, int height) + { + var inputPaths = ProjectPaths(paths, 4); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + var iSlice = Convert.ToInt32(width * 0.225); + int iTrans = Convert.ToInt32(height * .25); + int iHeight = Convert.ToInt32(height * .65); + var horizontalImagePadding = Convert.ToInt32(width * 0.0275); + + foreach (var element in wandImages.ImageList) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = blackPixelWand; + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .05)); + } + } + } + } + } + } + + return wand; + } + } + + private MagickWand BuildPosterCollageWandWithText(IEnumerable<string> paths, string label, int width, int height) + { + var inputPaths = ProjectPaths(paths, 4); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + using (var fcolor = new PixelWand(ColorName.White)) + { + draw.FillColor = fcolor; + draw.Font = MontserratLightFont; + draw.FontSize = 60; + draw.FontWeight = FontWeightType.LightStyle; + draw.TextAntialias = true; + } + + var fontMetrics = wand.QueryFontMetrics(draw, label); + var textContainerY = Convert.ToInt32(height * .165); + wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, label); + + var iSlice = Convert.ToInt32(width * 0.225); + int iTrans = Convert.ToInt32(height * 0.2); + int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296); + var horizontalImagePadding = Convert.ToInt32(width * 0.0275); + + foreach (var element in wandImages.ImageList) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = new PixelWand("none", 1); + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852)); + } + } + } + } + } + } + + return wand; + } + } + + private MagickWand BuildThumbCollageWand(IEnumerable<string> paths, int width, int height) + { + var inputPaths = ProjectPaths(paths, 8); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + var iSlice = Convert.ToInt32(width * .1166666667); + int iTrans = Convert.ToInt32(height * .25); + int iHeight = Convert.ToInt32(height * .62); + var horizontalImagePadding = Convert.ToInt32(width * 0.0125); + + foreach (var element in wandImages.ImageList) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = blackPixelWand; + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .085)); + } + } + } + } + } + } + + return wand; + } + } + + private MagickWand BuildSquareCollageWand(IEnumerable<string> paths, int width, int height) + { + var inputPaths = ProjectPaths(paths, 4); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + var iSlice = Convert.ToInt32(width * .225); + int iTrans = Convert.ToInt32(height * .25); + int iHeight = Convert.ToInt32(height * .63); + var horizontalImagePadding = Convert.ToInt32(width * 0.02); + + foreach (var element in wandImages.ImageList) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = blackPixelWand; + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .07)); + } + } + } + } + } + } + + return wand; + } + } + + private MagickWand BuildSquareCollageWandWithText(IEnumerable<string> paths, string label, int width, int height) + { + var inputPaths = ProjectPaths(paths, 4); + using (var wandImages = new MagickWand(inputPaths)) + { + var wand = new MagickWand(width, height); + wand.OpenImage("gradient:#111111-#111111"); + using (var draw = new DrawingWand()) + { + using (var fcolor = new PixelWand(ColorName.White)) + { + draw.FillColor = fcolor; + draw.Font = MontserratLightFont; + draw.FontSize = 60; + draw.FontWeight = FontWeightType.LightStyle; + draw.TextAntialias = true; + } + + var fontMetrics = wand.QueryFontMetrics(draw, label); + var textContainerY = Convert.ToInt32(height * .165); + wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, label); + + var iSlice = Convert.ToInt32(width * .225); + int iTrans = Convert.ToInt32(height * 0.2); + int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296); + var horizontalImagePadding = Convert.ToInt32(width * 0.02); + + foreach (var element in wandImages.ImageList) + { + int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height); + element.Gravity = GravityType.CenterGravity; + element.BackgroundColor = new PixelWand("none", 1); + element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter); + int ix = (int)Math.Abs((iWidth - iSlice) / 2); + element.CropImage(iSlice, iHeight, ix, 0); + + element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0); + } + + wandImages.SetFirstIterator(); + using (var wandList = wandImages.AppendImages()) + { + wandList.CurrentImage.TrimImage(1); + using (var mwr = wandList.CloneMagickWand()) + { + using (var blackPixelWand = new PixelWand(ColorName.Black)) + { + using (var greyPixelWand = new PixelWand(ColorName.Grey70)) + { + mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1); + mwr.CurrentImage.FlipImage(); + + mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel; + mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand); + + using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans)) + { + mwg.OpenImage("gradient:black-none"); + var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111); + mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing); + + wandList.AddImage(mwr); + int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2; + wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852)); + } + } + } + } + } + } + + return wand; + } + } + + private string MontserratLightFont + { + get { return PlayedIndicatorDrawer.ExtractFont("MontserratLight.otf", _appPaths); } + } + } +} diff --git a/Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs b/Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs new file mode 100644 index 0000000000..dd25004d66 --- /dev/null +++ b/Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs @@ -0,0 +1,70 @@ +using ImageMagickSharp; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Drawing; +using System.Globalization; + +namespace Emby.Drawing.ImageMagick +{ + public class UnplayedCountIndicator + { + private const int OffsetFromTopRightCorner = 38; + + private readonly IApplicationPaths _appPaths; + + public UnplayedCountIndicator(IApplicationPaths appPaths) + { + _appPaths = appPaths; + } + + public void DrawUnplayedCountIndicator(MagickWand wand, ImageSize imageSize, int count) + { + var x = imageSize.Width - OffsetFromTopRightCorner; + var text = count.ToString(CultureInfo.InvariantCulture); + + using (var draw = new DrawingWand()) + { + using (PixelWand pixel = new PixelWand()) + { + pixel.Color = "#52B54B"; + pixel.Opacity = 0.2; + draw.FillColor = pixel; + draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20); + + pixel.Opacity = 0; + pixel.Color = "white"; + draw.FillColor = pixel; + draw.Font = PlayedIndicatorDrawer.ExtractFont("robotoregular.ttf", _appPaths); + draw.FontStyle = FontStyleType.NormalStyle; + draw.TextAlignment = TextAlignType.CenterAlign; + draw.FontWeight = FontWeightType.RegularStyle; + draw.TextAntialias = true; + + var fontSize = 30; + var y = OffsetFromTopRightCorner + 11; + + if (text.Length == 1) + { + x += 1; + } + else if (text.Length == 2) + { + x += 1; + } + else if (text.Length >= 3) + { + //x += 1; + y -= 2; + fontSize = 24; + } + + draw.FontSize = fontSize; + draw.DrawAnnotation(x, y, text); + + draw.FillColor = pixel; + wand.CurrentImage.DrawImage(draw); + } + + } + } + } +} diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs new file mode 100644 index 0000000000..c7d06559ac --- /dev/null +++ b/Emby.Drawing/ImageProcessor.cs @@ -0,0 +1,768 @@ +using Emby.Drawing.Common; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.IO; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Emby.Drawing +{ + /// <summary> + /// Class ImageProcessor + /// </summary> + public class ImageProcessor : IImageProcessor, IDisposable + { + /// <summary> + /// The us culture + /// </summary> + protected readonly CultureInfo UsCulture = new CultureInfo("en-US"); + + /// <summary> + /// The _cached imaged sizes + /// </summary> + private readonly ConcurrentDictionary<Guid, ImageSize> _cachedImagedSizes; + + /// <summary> + /// Gets the list of currently registered image processors + /// Image processors are specialized metadata providers that run after the normal ones + /// </summary> + /// <value>The image enhancers.</value> + public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; } + + /// <summary> + /// The _logger + /// </summary> + private readonly ILogger _logger; + + private readonly IFileSystem _fileSystem; + private readonly IJsonSerializer _jsonSerializer; + private readonly IServerApplicationPaths _appPaths; + private readonly IImageEncoder _imageEncoder; + + public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IImageEncoder imageEncoder) + { + _logger = logger; + _fileSystem = fileSystem; + _jsonSerializer = jsonSerializer; + _imageEncoder = imageEncoder; + _appPaths = appPaths; + + _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite); + + Dictionary<Guid, ImageSize> sizeDictionary; + + try + { + sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ?? + new Dictionary<Guid, ImageSize>(); + } + catch (FileNotFoundException) + { + // No biggie + sizeDictionary = new Dictionary<Guid, ImageSize>(); + } + catch (DirectoryNotFoundException) + { + // No biggie + sizeDictionary = new Dictionary<Guid, ImageSize>(); + } + catch (Exception ex) + { + logger.ErrorException("Error parsing image size cache file", ex); + + sizeDictionary = new Dictionary<Guid, ImageSize>(); + } + + _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary); + } + + public string[] SupportedInputFormats + { + get + { + return _imageEncoder.SupportedInputFormats; + } + } + + private string ResizedImageCachePath + { + get + { + return Path.Combine(_appPaths.ImageCachePath, "resized-images"); + } + } + + private string EnhancedImageCachePath + { + get + { + return Path.Combine(_appPaths.ImageCachePath, "enhanced-images"); + } + } + + private string CroppedWhitespaceImageCachePath + { + get + { + return Path.Combine(_appPaths.ImageCachePath, "cropped-images"); + } + } + + public void AddParts(IEnumerable<IImageEnhancer> enhancers) + { + ImageEnhancers = enhancers.ToArray(); + } + + public async Task ProcessImage(ImageProcessingOptions options, Stream toStream) + { + var file = await ProcessImage(options).ConfigureAwait(false); + + using (var fileStream = _fileSystem.GetFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, true)) + { + await fileStream.CopyToAsync(toStream).ConfigureAwait(false); + } + } + + public ImageFormat[] GetSupportedImageOutputFormats() + { + return _imageEncoder.SupportedOutputFormats; + } + + public async Task<string> ProcessImage(ImageProcessingOptions options) + { + if (options == null) + { + throw new ArgumentNullException("options"); + } + + var originalImagePath = options.Image.Path; + + if (options.HasDefaultOptions(originalImagePath) && options.Enhancers.Count == 0 && !options.CropWhiteSpace) + { + // Just spit out the original file if all the options are default + return originalImagePath; + } + + var dateModified = options.Image.DateModified; + var length = options.Image.Length; + + if (options.CropWhiteSpace) + { + var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified, length).ConfigureAwait(false); + + originalImagePath = tuple.Item1; + dateModified = tuple.Item2; + length = tuple.Item3; + } + + if (options.Enhancers.Count > 0) + { + var tuple = await GetEnhancedImage(new ItemImageInfo + { + Length = length, + DateModified = dateModified, + Type = options.Image.Type, + Path = originalImagePath + + }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false); + + originalImagePath = tuple.Item1; + dateModified = tuple.Item2; + length = tuple.Item3; + } + + var originalImageSize = GetImageSize(originalImagePath, dateModified); + + // Determine the output size based on incoming parameters + var newSize = DrawingUtils.Resize(originalImageSize, options.Width, options.Height, options.MaxWidth, options.MaxHeight); + + if (options.HasDefaultOptionsWithoutSize(originalImagePath) && newSize.Equals(originalImageSize) && options.Enhancers.Count == 0) + { + // Just spit out the original file if the new size equals the old + return originalImagePath; + } + + var quality = options.Quality ?? 90; + + var outputFormat = GetOutputFormat(options.OutputFormat); + var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, length, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor); + + var semaphore = GetLock(cacheFilePath); + + await semaphore.WaitAsync().ConfigureAwait(false); + + try + { + CheckDisposed(); + + if (!File.Exists(cacheFilePath)) + { + var newWidth = Convert.ToInt32(newSize.Width); + var newHeight = Convert.ToInt32(newSize.Height); + + Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); + + _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, newWidth, newHeight, quality, options); + } + } + finally + { + semaphore.Release(); + } + + return cacheFilePath; + } + + private ImageFormat GetOutputFormat(ImageFormat requestedFormat) + { + if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp)) + { + return ImageFormat.Png; + } + + return requestedFormat; + } + + /// <summary> + /// Crops whitespace from an image, caches the result, and returns the cached path + /// </summary> + private async Task<Tuple<string, DateTime, long>> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified, long length) + { + var name = originalImagePath; + name += "datemodified=" + dateModified.Ticks; + name += "length=" + length; + + var croppedImagePath = GetCachePath(CroppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath)); + + var semaphore = GetLock(croppedImagePath); + + await semaphore.WaitAsync().ConfigureAwait(false); + + // Check again in case of contention + if (File.Exists(croppedImagePath)) + { + semaphore.Release(); + return GetResult(croppedImagePath); + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath)); + + _imageEncoder.CropWhiteSpace(originalImagePath, croppedImagePath); + } + catch (Exception ex) + { + // We have to have a catch-all here because some of the .net image methods throw a plain old Exception + _logger.ErrorException("Error cropping image {0}", ex, originalImagePath); + + return new Tuple<string, DateTime, long>(originalImagePath, dateModified, length); + } + finally + { + semaphore.Release(); + } + + return GetResult(croppedImagePath); + } + + private Tuple<string, DateTime, long> GetResult(string path) + { + var file = new FileInfo(path); + + return new Tuple<string, DateTime, long>(path, _fileSystem.GetLastWriteTimeUtc(file), file.Length); + } + + /// <summary> + /// Increment this when there's a change requiring caches to be invalidated + /// </summary> + private const string Version = "3"; + + /// <summary> + /// Gets the cache file path based on a set of parameters + /// </summary> + private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, long length, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, string backgroundColor) + { + var filename = originalPath; + + filename += "width=" + outputSize.Width; + + filename += "height=" + outputSize.Height; + + filename += "quality=" + quality; + + filename += "datemodified=" + dateModified.Ticks; + filename += "length=" + length; + + filename += "f=" + format; + + if (addPlayedIndicator) + { + filename += "pl=true"; + } + + if (percentPlayed > 0) + { + filename += "p=" + percentPlayed; + } + + if (unwatchedCount.HasValue) + { + filename += "p=" + unwatchedCount.Value; + } + + if (!string.IsNullOrEmpty(backgroundColor)) + { + filename += "b=" + backgroundColor; + } + + filename += "v=" + Version; + + return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower()); + } + + /// <summary> + /// Gets the size of the image. + /// </summary> + /// <param name="path">The path.</param> + /// <returns>ImageSize.</returns> + public ImageSize GetImageSize(string path) + { + return GetImageSize(path, File.GetLastWriteTimeUtc(path)); + } + + public ImageSize GetImageSize(ItemImageInfo info) + { + return GetImageSize(info.Path, info.DateModified); + } + + /// <summary> + /// Gets the size of the image. + /// </summary> + /// <param name="path">The path.</param> + /// <param name="imageDateModified">The image date modified.</param> + /// <returns>ImageSize.</returns> + /// <exception cref="System.ArgumentNullException">path</exception> + private ImageSize GetImageSize(string path, DateTime imageDateModified) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException("path"); + } + + var name = path + "datemodified=" + imageDateModified.Ticks; + + ImageSize size; + + var cacheHash = name.GetMD5(); + + if (!_cachedImagedSizes.TryGetValue(cacheHash, out size)) + { + size = GetImageSizeInternal(path); + + _cachedImagedSizes.AddOrUpdate(cacheHash, size, (keyName, oldValue) => size); + } + + return size; + } + + /// <summary> + /// Gets the image size internal. + /// </summary> + /// <param name="path">The path.</param> + /// <returns>ImageSize.</returns> + private ImageSize GetImageSizeInternal(string path) + { + ImageSize size; + + try + { + size = ImageHeader.GetDimensions(path, _logger, _fileSystem); + } + catch + { + _logger.Info("Failed to read image header for {0}. Doing it the slow way.", path); + + CheckDisposed(); + + size = _imageEncoder.GetImageSize(path); + } + + StartSaveImageSizeTimer(); + + return size; + } + + private readonly Timer _saveImageSizeTimer; + private const int SaveImageSizeTimeout = 5000; + private readonly object _saveImageSizeLock = new object(); + private void StartSaveImageSizeTimer() + { + _saveImageSizeTimer.Change(SaveImageSizeTimeout, Timeout.Infinite); + } + + private void SaveImageSizeCallback(object state) + { + lock (_saveImageSizeLock) + { + try + { + var path = ImageSizeFile; + Directory.CreateDirectory(Path.GetDirectoryName(path)); + _jsonSerializer.SerializeToFile(_cachedImagedSizes, path); + } + catch (Exception ex) + { + _logger.ErrorException("Error saving image size file", ex); + } + } + } + + private string ImageSizeFile + { + get + { + return Path.Combine(_appPaths.DataPath, "imagesizes.json"); + } + } + + /// <summary> + /// Gets the image cache tag. + /// </summary> + /// <param name="item">The item.</param> + /// <param name="image">The image.</param> + /// <returns>Guid.</returns> + /// <exception cref="System.ArgumentNullException">item</exception> + public string GetImageCacheTag(IHasImages item, ItemImageInfo image) + { + if (item == null) + { + throw new ArgumentNullException("item"); + } + + if (image == null) + { + throw new ArgumentNullException("image"); + } + + var supportedEnhancers = GetSupportedEnhancers(item, image.Type); + + return GetImageCacheTag(item, image, supportedEnhancers.ToList()); + } + + /// <summary> + /// Gets the image cache tag. + /// </summary> + /// <param name="item">The item.</param> + /// <param name="image">The image.</param> + /// <param name="imageEnhancers">The image enhancers.</param> + /// <returns>Guid.</returns> + /// <exception cref="System.ArgumentNullException">item</exception> + public string GetImageCacheTag(IHasImages item, ItemImageInfo image, List<IImageEnhancer> imageEnhancers) + { + if (item == null) + { + throw new ArgumentNullException("item"); + } + + if (imageEnhancers == null) + { + throw new ArgumentNullException("imageEnhancers"); + } + + if (image == null) + { + throw new ArgumentNullException("image"); + } + + var originalImagePath = image.Path; + var dateModified = image.DateModified; + var imageType = image.Type; + var length = image.Length; + + // Optimization + if (imageEnhancers.Count == 0) + { + return (originalImagePath + dateModified.Ticks + string.Empty + length).GetMD5().ToString("N"); + } + + // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes + var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList(); + cacheKeys.Add(originalImagePath + dateModified.Ticks + string.Empty + length); + + return string.Join("|", cacheKeys.ToArray()).GetMD5().ToString("N"); + } + + /// <summary> + /// Gets the enhanced image. + /// </summary> + /// <param name="item">The item.</param> + /// <param name="imageType">Type of the image.</param> + /// <param name="imageIndex">Index of the image.</param> + /// <returns>Task{System.String}.</returns> + public async Task<string> GetEnhancedImage(IHasImages item, ImageType imageType, int imageIndex) + { + var enhancers = GetSupportedEnhancers(item, imageType).ToList(); + + var imageInfo = item.GetImageInfo(imageType, imageIndex); + + var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers); + + return result.Item1; + } + + private async Task<Tuple<string, DateTime, long>> GetEnhancedImage(ItemImageInfo image, + IHasImages item, + int imageIndex, + List<IImageEnhancer> enhancers) + { + var originalImagePath = image.Path; + var dateModified = image.DateModified; + var imageType = image.Type; + var length = image.Length; + + try + { + var cacheGuid = GetImageCacheTag(item, image, enhancers); + + // Enhance if we have enhancers + var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false); + + // If the path changed update dateModified + if (!ehnancedImagePath.Equals(originalImagePath, StringComparison.OrdinalIgnoreCase)) + { + return GetResult(ehnancedImagePath); + } + } + catch (Exception ex) + { + _logger.Error("Error enhancing image", ex); + } + + return new Tuple<string, DateTime, long>(originalImagePath, dateModified, length); + } + + /// <summary> + /// Gets the enhanced image internal. + /// </summary> + /// <param name="originalImagePath">The original image path.</param> + /// <param name="item">The item.</param> + /// <param name="imageType">Type of the image.</param> + /// <param name="imageIndex">Index of the image.</param> + /// <param name="supportedEnhancers">The supported enhancers.</param> + /// <param name="cacheGuid">The cache unique identifier.</param> + /// <returns>Task<System.String>.</returns> + /// <exception cref="ArgumentNullException"> + /// originalImagePath + /// or + /// item + /// </exception> + private async Task<string> GetEnhancedImageInternal(string originalImagePath, + IHasImages item, + ImageType imageType, + int imageIndex, + IEnumerable<IImageEnhancer> supportedEnhancers, + string cacheGuid) + { + if (string.IsNullOrEmpty(originalImagePath)) + { + throw new ArgumentNullException("originalImagePath"); + } + + if (item == null) + { + throw new ArgumentNullException("item"); + } + + // All enhanced images are saved as png to allow transparency + var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png"); + + var semaphore = GetLock(enhancedImagePath); + + await semaphore.WaitAsync().ConfigureAwait(false); + + // Check again in case of contention + if (File.Exists(enhancedImagePath)) + { + semaphore.Release(); + return enhancedImagePath; + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath)); + await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false); + } + finally + { + semaphore.Release(); + } + + return enhancedImagePath; + } + + /// <summary> + /// Executes the image enhancers. + /// </summary> + /// <param name="imageEnhancers">The image enhancers.</param> + /// <param name="inputPath">The input path.</param> + /// <param name="outputPath">The output path.</param> + /// <param name="item">The item.</param> + /// <param name="imageType">Type of the image.</param> + /// <param name="imageIndex">Index of the image.</param> + /// <returns>Task{EnhancedImage}.</returns> + private async Task ExecuteImageEnhancers(IEnumerable<IImageEnhancer> imageEnhancers, string inputPath, string outputPath, IHasImages item, ImageType imageType, int imageIndex) + { + // Run the enhancers sequentially in order of priority + foreach (var enhancer in imageEnhancers) + { + var typeName = enhancer.GetType().Name; + + try + { + await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.ErrorException("{0} failed enhancing {1}", ex, typeName, item.Name); + + throw; + } + + // Feed the output into the next enhancer as input + inputPath = outputPath; + } + } + + /// <summary> + /// The _semaphoreLocks + /// </summary> + private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(); + + /// <summary> + /// Gets the lock. + /// </summary> + /// <param name="filename">The filename.</param> + /// <returns>System.Object.</returns> + private SemaphoreSlim GetLock(string filename) + { + return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); + } + + /// <summary> + /// Gets the cache path. + /// </summary> + /// <param name="path">The path.</param> + /// <param name="uniqueName">Name of the unique.</param> + /// <param name="fileExtension">The file extension.</param> + /// <returns>System.String.</returns> + /// <exception cref="System.ArgumentNullException"> + /// path + /// or + /// uniqueName + /// or + /// fileExtension + /// </exception> + public string GetCachePath(string path, string uniqueName, string fileExtension) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException("path"); + } + if (string.IsNullOrEmpty(uniqueName)) + { + throw new ArgumentNullException("uniqueName"); + } + + if (string.IsNullOrEmpty(fileExtension)) + { + throw new ArgumentNullException("fileExtension"); + } + + var filename = uniqueName.GetMD5() + fileExtension; + + return GetCachePath(path, filename); + } + + /// <summary> + /// Gets the cache path. + /// </summary> + /// <param name="path">The path.</param> + /// <param name="filename">The filename.</param> + /// <returns>System.String.</returns> + /// <exception cref="System.ArgumentNullException"> + /// path + /// or + /// filename + /// </exception> + public string GetCachePath(string path, string filename) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException("path"); + } + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException("filename"); + } + + var prefix = filename.Substring(0, 1); + + path = Path.Combine(path, prefix); + + return Path.Combine(path, filename); + } + + public void CreateImageCollage(ImageCollageOptions options) + { + _imageEncoder.CreateImageCollage(options); + } + + public IEnumerable<IImageEnhancer> GetSupportedEnhancers(IHasImages item, ImageType imageType) + { + return ImageEnhancers.Where(i => + { + try + { + return i.Supports(item, imageType); + } + catch (Exception ex) + { + _logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name); + + return false; + } + + }); + } + + private bool _disposed; + public void Dispose() + { + _disposed = true; + _imageEncoder.Dispose(); + _saveImageSizeTimer.Dispose(); + } + + private void CheckDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(GetType().Name); + } + } + } +} diff --git a/Emby.Drawing/Properties/AssemblyInfo.cs b/Emby.Drawing/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..fba168d034 --- /dev/null +++ b/Emby.Drawing/Properties/AssemblyInfo.cs @@ -0,0 +1,31 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Emby.Drawing")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Emby.Drawing")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("87b6f14e-16d8-4a58-a553-fd9945e47458")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +//
\ No newline at end of file diff --git a/Emby.Drawing/packages.config b/Emby.Drawing/packages.config new file mode 100644 index 0000000000..a331f20b3a --- /dev/null +++ b/Emby.Drawing/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="ImageMagickSharp" version="1.0.0.14" targetFramework="net45" /> +</packages>
\ No newline at end of file |
