// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // // // Encapsulates methods for processing image files. // // -------------------------------------------------------------------------------------------------------------------- namespace ImageProcessor { #region Using using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using ImageProcessor.Core.Common.Exceptions; using ImageProcessor.Imaging; using ImageProcessor.Imaging.Filters; using ImageProcessor.Imaging.Formats; using ImageProcessor.Processors; #endregion /// /// Encapsulates methods for processing image files. /// public class ImageFactory : IDisposable { #region Fields /// /// The default quality for image files. /// private const int DefaultQuality = 90; /// /// The backup supported image format. /// private ISupportedImageFormat backupFormat; /// /// A value indicating whether this instance of the given entity has been disposed. /// /// if this instance has been disposed; otherwise, . /// /// If the entity is disposed, it must not be disposed a second /// time. The isDisposed field is set the first time the entity /// is disposed. If the isDisposed field is true, then the Dispose() /// method will not dispose again. This help not to prolong the entity's /// life in the Garbage Collector. /// private bool isDisposed; #endregion #region Constructors /// /// Initializes a new instance of the class. /// /// /// Whether to preserve exif metadata. Defaults to false. /// public ImageFactory(bool preserveExifData = false) { this.PreserveExifData = preserveExifData; this.ExifPropertyItems = new ConcurrentDictionary(); } #endregion #region Destructors /// /// Finalizes an instance of the ImageFactory class. /// /// /// Use C# destructor syntax for finalization code. /// This destructor will run only if the Dispose method /// does not get called. /// It gives your base class the opportunity to finalize. /// Do not provide destructors in types derived from this class. /// ~ImageFactory() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. this.Dispose(false); } #endregion #region Properties /// /// Gets the path to the local image for manipulation. /// public string ImagePath { get; private set; } /// /// Gets the query-string parameters for web image manipulation. /// public string QueryString { get; private set; } /// /// Gets a value indicating whether the image factory should process the file. /// public bool ShouldProcess { get; private set; } /// /// Gets the supported image format. /// public ISupportedImageFormat CurrentImageFormat { get; private set; } /// /// Gets or sets a value indicating whether to preserve exif metadata. /// public bool PreserveExifData { get; set; } /// /// Gets or sets the exif property items. /// public ConcurrentDictionary ExifPropertyItems { get; set; } /// /// Gets or sets the local image for manipulation. /// internal Image Image { get; set; } /// /// Gets or sets the original extension. /// internal string OriginalExtension { get; set; } /// /// Gets or sets the memory stream for storing any input stream to prevent disposal. /// internal MemoryStream InputStream { get; set; } #endregion #region Methods /// /// Loads the image to process. Always call this method first. /// /// /// The containing the image information. /// /// /// The current instance of the class. /// public ImageFactory Load(MemoryStream memoryStream) { ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream); if (format == null) { throw new ImageFormatException("Input stream is not a supported format."); } this.backupFormat = format; this.CurrentImageFormat = format; // Set our image as the memory stream value. this.Image = format.Load(memoryStream); // Store the stream so we can dispose of it later. this.InputStream = memoryStream; // Set the other properties. format.Quality = DefaultQuality; format.IsIndexed = ImageUtils.IsIndexed(this.Image); if (this.PreserveExifData) { foreach (PropertyItem propertyItem in this.Image.PropertyItems) { this.ExifPropertyItems[propertyItem.Id] = propertyItem; } } this.ShouldProcess = true; return this; } /// /// Loads the image to process. Always call this method first. /// /// The absolute path to the image to load. /// /// The current instance of the class. /// public ImageFactory Load(string imagePath) { // Remove any querystring parameters passed by web requests. string[] paths = imagePath.Split('?'); string path = paths[0]; string query = string.Empty; if (paths.Length > 1) { query = paths[1]; } if (File.Exists(path)) { this.ImagePath = path; this.QueryString = query; // Open a file stream to prevent the need for lock. using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { ISupportedImageFormat format = FormatUtilities.GetFormat(fileStream); if (format == null) { throw new ImageFormatException("Input stream is not a supported format."); } this.backupFormat = format; this.CurrentImageFormat = format; MemoryStream memoryStream = new MemoryStream(); // Copy the stream. fileStream.CopyTo(memoryStream); // Set the position to 0 afterwards. fileStream.Position = memoryStream.Position = 0; // Set our image as the memory stream value. this.Image = format.Load(memoryStream); // Store the stream so we can dispose of it later. this.InputStream = memoryStream; // Set the other properties. format.Quality = DefaultQuality; format.IsIndexed = ImageUtils.IsIndexed(this.Image); this.OriginalExtension = Path.GetExtension(this.ImagePath); if (this.PreserveExifData) { foreach (PropertyItem propertyItem in this.Image.PropertyItems) { this.ExifPropertyItems[propertyItem.Id] = propertyItem; } } this.ShouldProcess = true; } } return this; } /// /// Resets the current image to its original loaded state. /// /// /// The current instance of the class. /// public ImageFactory Reset() { if (this.ShouldProcess) { // Set our new image as the memory stream value. Image newImage = Image.FromStream(this.InputStream, true); // Dispose and reassign the image. this.Image.Dispose(); this.Image = newImage; // Set the other properties. this.CurrentImageFormat = this.backupFormat; this.CurrentImageFormat.Quality = DefaultQuality; } return this; } #region Manipulation /// /// Adds a query-string to the image factory to allow auto-processing of remote files. /// /// The query-string parameter to process. /// /// The current instance of the class. /// public ImageFactory AddQueryString(string query) { // TODO: Remove this. if (this.ShouldProcess) { this.QueryString = query; } return this; } /// /// Changes the opacity of the current image. /// /// /// The percentage by which to alter the images opacity. /// Any integer between 0 and 100. /// /// /// The current instance of the class. /// public ImageFactory Alpha(int percentage) { if (this.ShouldProcess) { // Sanitize the input. if (percentage > 100 || percentage < 0) { percentage = 0; } Alpha alpha = new Alpha { DynamicParameter = percentage }; this.CurrentImageFormat.ApplyProcessor(alpha.ProcessImage, this); } return this; } /// /// Changes the brightness of the current image. /// /// /// The percentage by which to alter the images brightness. /// Any integer between -100 and 100. /// /// /// The current instance of the class. /// public ImageFactory Brightness(int percentage) { if (this.ShouldProcess) { // Sanitize the input. if (percentage > 100 || percentage < -100) { percentage = 0; } Brightness brightness = new Brightness { DynamicParameter = percentage }; this.CurrentImageFormat.ApplyProcessor(brightness.ProcessImage, this); } return this; } /// /// Constrains the current image, resizing it to fit within the given dimensions whilst keeping its aspect ratio. /// /// /// The containing the maximum width and height to set the image to. /// /// /// The current instance of the class. /// public ImageFactory Constrain(Size size) { if (this.ShouldProcess) { ResizeLayer layer = new ResizeLayer(size, Color.Transparent, ResizeMode.Max); return this.Resize(layer); } return this; } /// /// Changes the contrast of the current image. /// /// /// The percentage by which to alter the images contrast. /// Any integer between -100 and 100. /// /// /// The current instance of the class. /// public ImageFactory Contrast(int percentage) { if (this.ShouldProcess) { // Sanitize the input. if (percentage > 100 || percentage < -100) { percentage = 0; } Contrast contrast = new Contrast { DynamicParameter = percentage }; this.CurrentImageFormat.ApplyProcessor(contrast.ProcessImage, this); } return this; } /// /// Crops the current image to the given location and size. /// /// /// The containing the coordinates to crop the image to. /// /// /// The current instance of the class. /// public ImageFactory Crop(Rectangle rectangle) { if (this.ShouldProcess) { CropLayer cropLayer = new CropLayer(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom, CropMode.Pixels); return this.Crop(cropLayer); } return this; } /// /// Crops the current image to the given location and size. /// /// /// The containing the coordinates and mode to crop the image with. /// /// /// The current instance of the class. /// public ImageFactory Crop(CropLayer cropLayer) { if (this.ShouldProcess) { Crop crop = new Crop { DynamicParameter = cropLayer }; this.CurrentImageFormat.ApplyProcessor(crop.ProcessImage, this); } return this; } /// /// Applies a filter to the current image. /// /// /// The name of the filter to add to the image. /// /// /// The current instance of the class. /// [Obsolete("Will be removed in next major version. Filter(IMatrixFilter matrixFilter) instead.")] public ImageFactory Filter(string filterName) { if (this.ShouldProcess) { Filter filter = new Filter { DynamicParameter = filterName }; this.CurrentImageFormat.ApplyProcessor(filter.ProcessImage, this); } return this; } /// /// Applies a filter to the current image. Use the class to /// assign the correct filter. /// /// /// The of the filter to add to the image. /// /// /// The current instance of the class. /// public ImageFactory Filter(IMatrixFilter matrixFilter) { if (this.ShouldProcess) { Filter filter = new Filter { DynamicParameter = matrixFilter }; this.CurrentImageFormat.ApplyProcessor(filter.ProcessImage, this); } return this; } /// /// Flips the current image either horizontally or vertically. /// /// /// Whether to flip the image vertically. /// /// /// The current instance of the class. /// public ImageFactory Flip(bool flipVertically) { if (this.ShouldProcess) { RotateFlipType rotateFlipType = flipVertically == false ? RotateFlipType.RotateNoneFlipX : RotateFlipType.RotateNoneFlipY; Flip flip = new Flip { DynamicParameter = rotateFlipType }; this.CurrentImageFormat.ApplyProcessor(flip.ProcessImage, this); } return this; } /// /// Sets the output format of the current image to the matching . /// /// The . to set the image to. /// /// The current instance of the class. /// public ImageFactory Format(ISupportedImageFormat format) { if (this.ShouldProcess) { this.CurrentImageFormat = format; } return this; } /// /// Uses a Gaussian kernel to blur the current image. /// /// /// The sigma and threshold values applied to the kernel are /// 1.4 and 0 respectively. /// /// /// /// /// The size to set the Gaussian kernel to. /// /// /// The current instance of the class. /// public ImageFactory GaussianBlur(int size) { if (this.ShouldProcess && size > 0) { GaussianLayer layer = new GaussianLayer(size); return this.GaussianBlur(layer); } return this; } /// /// Uses a Gaussian kernel to blur the current image. /// /// /// The for applying sharpening and /// blurring methods to an image. /// /// /// The current instance of the class. /// public ImageFactory GaussianBlur(GaussianLayer gaussianLayer) { if (this.ShouldProcess) { GaussianBlur gaussianBlur = new GaussianBlur { DynamicParameter = gaussianLayer }; this.CurrentImageFormat.ApplyProcessor(gaussianBlur.ProcessImage, this); } return this; } /// /// Uses a Gaussian kernel to sharpen the current image. /// /// /// The sigma and threshold values applied to the kernel are /// 1.4 and 0 respectively. /// /// /// /// /// The size to set the Gaussian kernel to. /// /// /// The current instance of the class. /// public ImageFactory GaussianSharpen(int size) { if (this.ShouldProcess && size > 0) { GaussianLayer layer = new GaussianLayer(size); return this.GaussianSharpen(layer); } return this; } /// /// Uses a Gaussian kernel to sharpen the current image. /// /// /// The for applying sharpening and /// blurring methods to an image. /// /// /// The current instance of the class. /// public ImageFactory GaussianSharpen(GaussianLayer gaussianLayer) { if (this.ShouldProcess) { GaussianSharpen gaussianSharpen = new GaussianSharpen { DynamicParameter = gaussianLayer }; this.CurrentImageFormat.ApplyProcessor(gaussianSharpen.ProcessImage, this); } return this; } /// /// Alters the output quality of the current image. /// /// This method will only effect the output quality of jpeg images /// /// /// A value between 1 and 100 to set the quality to. /// /// The current instance of the class. /// public ImageFactory Quality(int percentage) { if (this.ShouldProcess) { this.CurrentImageFormat.Quality = percentage; } return this; } /// /// Resizes the current image to the given dimensions. /// /// /// The containing the width and height to set the image to. /// /// /// The current instance of the class. /// public ImageFactory Resize(Size size) { if (this.ShouldProcess) { int width = size.Width; int height = size.Height; ResizeLayer resizeLayer = new ResizeLayer(new Size(width, height)); return this.Resize(resizeLayer); } return this; } /// /// Resizes the current image to the given dimensions. /// /// /// The containing the properties required to resize the image. /// /// /// The current instance of the class. /// public ImageFactory Resize(ResizeLayer resizeLayer) { if (this.ShouldProcess) { var resizeSettings = new Dictionary { { "MaxWidth", resizeLayer.Size.Width.ToString("G") }, { "MaxHeight", resizeLayer.Size.Height.ToString("G") } }; Resize resize = new Resize { DynamicParameter = resizeLayer, Settings = resizeSettings }; this.CurrentImageFormat.ApplyProcessor(resize.ProcessImage, this); } return this; } /// /// Rotates the current image by the given angle. /// /// /// The angle at which to rotate the image in degrees. /// /// /// The current instance of the class. /// public ImageFactory Rotate(int degrees) { if (this.ShouldProcess) { // Sanitize the input. if (degrees > 360 || degrees < 0) { degrees = 0; } Rotate rotate = new Rotate { DynamicParameter = degrees }; this.CurrentImageFormat.ApplyProcessor(rotate.ProcessImage, this); } return this; } /// /// Adds rounded corners to the current image. /// /// /// The containing the properties to round corners on the image. /// /// /// The current instance of the class. /// public ImageFactory RoundedCorners(RoundedCornerLayer roundedCornerLayer) { if (this.ShouldProcess) { if (roundedCornerLayer.Radius < 0) { roundedCornerLayer.Radius = 0; } RoundedCorners roundedCorners = new RoundedCorners { DynamicParameter = roundedCornerLayer }; this.CurrentImageFormat.ApplyProcessor(roundedCorners.ProcessImage, this); } return this; } /// /// Changes the saturation of the current image. /// /// /// The percentage by which to alter the images saturation. /// Any integer between -100 and 100. /// /// /// The current instance of the class. /// public ImageFactory Saturation(int percentage) { if (this.ShouldProcess) { // Sanitize the input. if (percentage > 100 || percentage < -100) { percentage = 0; } Saturation saturate = new Saturation { DynamicParameter = percentage }; this.CurrentImageFormat.ApplyProcessor(saturate.ProcessImage, this); } return this; } /// /// Tints the current image with the given color. /// /// /// The to tint the image with. /// /// /// The current instance of the class. /// public ImageFactory Tint(Color color) { if (this.ShouldProcess) { Tint tint = new Tint { DynamicParameter = color }; this.CurrentImageFormat.ApplyProcessor(tint.ProcessImage, this); } return this; } /// /// Adds a vignette image effect to the current image. /// /// /// The current instance of the class. /// public ImageFactory Vignette() { if (this.ShouldProcess) { Vignette vignette = new Vignette(); this.CurrentImageFormat.ApplyProcessor(vignette.ProcessImage, this); } return this; } /// /// Adds a text based watermark to the current image. /// /// /// The containing the properties necessary to add /// the text based watermark to the image. /// /// /// The current instance of the class. /// public ImageFactory Watermark(TextLayer textLayer) { if (this.ShouldProcess) { Watermark watermark = new Watermark { DynamicParameter = textLayer }; this.CurrentImageFormat.ApplyProcessor(watermark.ProcessImage, this); } return this; } #endregion /// /// Saves the current image to the specified file path. If the extension does not /// match the correct extension for the current format it will be replaced by the /// correct default value. /// /// The path to save the image to. /// /// The current instance of the class. /// public ImageFactory Save(string filePath) { if (this.ShouldProcess) { // We need to check here if the path has an extension and remove it if so. // This is so we can add the correct image format. int length = filePath.LastIndexOf(".", StringComparison.Ordinal); string extension = Path.GetExtension(filePath).TrimStart('.'); string fallback = this.CurrentImageFormat.DefaultExtension; if (extension != fallback && !this.CurrentImageFormat.FileExtensions.Contains(extension)) { filePath = length == -1 ? string.Format("{0}.{1}", filePath, fallback) : filePath.Substring(0, length + 1) + fallback; } // ReSharper disable once AssignNullToNotNullAttribute DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); if (!directoryInfo.Exists) { directoryInfo.Create(); } this.Image = this.CurrentImageFormat.Save(filePath, this.Image); } return this; } /// /// Saves the current image to the specified output stream. /// /// /// The to save the image information to. /// /// /// The current instance of the class. /// public ImageFactory Save(MemoryStream memoryStream) { if (this.ShouldProcess) { this.Image = this.CurrentImageFormat.Save(memoryStream, this.Image); } return this; } #region IDisposable Members /// /// Disposes the object and frees resources for the Garbage Collector. /// public void Dispose() { this.Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// /// Disposes the object and frees resources for the Garbage Collector. /// /// If true, the object gets disposed. protected virtual void Dispose(bool disposing) { if (this.isDisposed) { return; } if (disposing) { // Dispose of any managed resources here. if (this.Image != null) { // Dispose of the memory stream from Load and the image. if (this.InputStream != null) { this.InputStream.Dispose(); this.InputStream = null; } this.Image.Dispose(); this.Image = null; } } // Call the appropriate methods to clean up // unmanaged resources here. // Note disposing is done. this.isDisposed = true; } #endregion #endregion } }