diff options
| author | Luke Pulverenti <luke.pulverenti@gmail.com> | 2015-04-08 10:38:02 -0400 |
|---|---|---|
| committer | Luke Pulverenti <luke.pulverenti@gmail.com> | 2015-04-08 10:38:02 -0400 |
| commit | 4820fe80971c83cde97a445e45b9e0b1952b0d90 (patch) | |
| tree | 4009bb413065f08471a9c7546e4330fe1d8713c9 /Emby.Drawing/GDI | |
| parent | 78e96917e12abb963301957607da4a738f27df58 (diff) | |
added drawing project
Diffstat (limited to 'Emby.Drawing/GDI')
| -rw-r--r-- | Emby.Drawing/GDI/GDIImageEncoder.cs | 233 | ||||
| -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 |
5 files changed, 566 insertions, 0 deletions
diff --git a/Emby.Drawing/GDI/GDIImageEncoder.cs b/Emby.Drawing/GDI/GDIImageEncoder.cs new file mode 100644 index 0000000000..c6537fc436 --- /dev/null +++ b/Emby.Drawing/GDI/GDIImageEncoder.cs @@ -0,0 +1,233 @@ +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 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) + { + } + + public void Dispose() + { + } + } +} 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); + } + } + } + } + } +} |
