Open-source free. NET image instant processing component ImageProcessor,. netimageprocessor

Source: Internet
Author: User

Open-source free. NET image instant processing component ImageProcessor,. netimageprocessor

Undertake the previous component series, which is intended to be introduced. NET-related components, so that you can have a better choice in the project, the Community has little introduction to third-party plug-ins, many blog posts mainly introduce some simple operations (many people say that the blog Park is now "hello world" and the quality of blog posts is declining, I think this is a bit overhead. Some blog posts do have a relatively elementary level, but many blog posts are still very in-depth, but are rarely noticed ), this component series mainly introduces some functional components with the core objects of this component.

The introduction of components is definitely not an article that can be described, because a component is developed for a long period of time by developers and can be described in a simple blog, the series of component introductions generally follow the components Background introduction, component usage introduction, core object introduction, and so on. If you are interested in components, you can have a deep understanding and learning.

Speak nonsense and start with the question.

We often process files in projects, such as uploading and downloading files. There will also be a lot of real-time operations on images. Here we will introduce a collection of lightweight libraries written in C #, which can be used by you. NET 4.5 + to dynamically process the image component, that is, ImageProcessor, used for instant image processing.. NET Library. (The open-source project team of the Organization will develop a. NET Core component in the second project after the first project runs in)

1. ImageProcessor component Overview

ImageProcessor is a collection of lightweight libraries written in C #. It allows you to use it. NET 4.5 + to dynamically process images, including two master libraries: ImageProcessor (for desktop and Application Use) ImageProcessor. web (ASP.. NET (dynamic image processing Extension). This component is fast, scalable, and easy to use. It is bundled with some powerful functions and is completely open-source. This component has two parts. Today we will mainly explain the ImageProcessor part. If you are interested in another one, you can understand it on your own.

ImageProcessor. Web adds a configurable HttpModule to the project, allowing instant processing of image files. This module also provides a file-and browser-based cache that can process millions of images, increase processing output and save valuable server memory. This component has the following functions: resize, rotate, rounded corner, flip, crop, watermark, filter, saturation, brightness, contrast, quality, format, inception, Gaussian blur, gaussian sharpening and transparency.

The current version of ImageProcessor. Web is 4.8.2. You can download the source code and DLL files (I suggest you download the source code. The benefits will not be described here ).

ImageProcessor. Web is a Web extension of ImageProcessor, allowing developers to use the Url API to query string parameters as instructions for image operations. The output of this process is a highly optimized network to ensure high performance of web projects. When ImageProcessor. Web is installed, the following nodes are added to Web. config by default

<add name = "ImageProcessorModule" type = "ImageProcessor.Web.HttpModules.ImageProcessingModule, ImageProcessor.Web" /> </ httpModules>
    This allows the library ImageProcessingModule to intercept local image processing requests. ImageProcessor.Web is highly configurable. Other configuration files can be added to the solution to retrieve, process, and cache images from multiple sources. You can view the documentation for the configuration settings of this component.

2. Overview of ImageProcessor component operation
  Introduces the relevant information of the component, here introduces the operation example of the component. The ImageFactory class provides methods for performing various operations on a given image. It has been carefully designed to prevent various memory leaks that usually occur when processing images in a high-performance manner. This makes it safe to use in desktop and web environments. ImageFactory automatically detects the correct file type for a given image, and the API for this class is fluent, which allows you to easily link methods to provide the desired output. For example, the following code loads, resizes, sets a new format, and saves a MemoryStream containing image information.

  public static void Image (string file)
        {
            if (string.IsNullOrEmpty (file))
            {
                throw new ArgumentNullException (file);
            }
            byte [] photoBytes = System.IO.File.ReadAllBytes (file);
            // Detection format
            ISupportedImageFormat format = new JpegFormat {Quality = 70};
            Size size = new Size (150, 0);
            using (MemoryStream inStream = new MemoryStream (photoBytes))
            {
                using (MemoryStream outStream = new MemoryStream ())
                {
                    // Initialize ImageFactory with overloading to retain EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory (true))
                    {
                        // Load, resize, set format and quality and save the image.
                        imageFactory.Load (inStream)
                                    .Resize (size)
                                    .Format (format)
                                    .Save (outStream);
                        // Perform corresponding operations on the obtained imageFactory object
                    }
                   // Operate on the obtained data stream
                }
            }
   For the operation of the picture, there are more operation methods, and the specific methods are as follows:

Method name Method operation instructions
Reset resets the current image to its original loading state
Alpha changes the opacity of the current image
AutoRotate performs automatic rotation to ensure that the final image of the rotation defined by EXIF is reflected
BitDepth changes the bit depth of the current image
Brightness Change the brightness of the current image
BackgroundColor Change the background color of the current image
Constrain constrains the current image, adjusts its size to fit the given size, while maintaining its aspect ratio
Contrast changes the contrast of the current image
Crop crops the current image to a given position and size
DetectEdges detects edges in the current image
Resolution Set the resolution of the image
EntropyCrop trims the image to the area of maximum entropy
Filter applies the filter to the current image
Flip flip the current image horizontally or vertically
Gamma adjusts the grayscale (light intensity) component of a given image
GaussianBlur uses Gaussian kernel to blur the current image
Hue changes the hue of the current image, changes the overall color
Halftone converts the current image to the CMYK halftone representation of the image
Quality changes the output quality of the current image
ReplaceColor replaces the color in the current image
Resize adjusts the current image to the given size
Rotate rotates the current image by a given angle
    The above only lists some main operation methods, and there are other methods that will not be introduced here. If you are interested, you can practice them yourself. Here are some core objects.

Three. ImageProcessor core object analysis
    After analysis, let's take a detailed look at the core methods and properties, and see if the source code is still beneficial.

  1.ImageFactory.Load ()
 public ImageFactory Load (string imagePath)
        {
            FileInfo fileInfo = new FileInfo (imagePath);
            if (fileInfo.Exists)
            {
                this.ImagePath = imagePath;
                using (FileStream fileStream = new FileStream (imagePath, FileMode.Open, FileAccess.Read))
                {
                    ISupportedImageFormat format = FormatUtilities.GetFormat (fileStream);
                    if (format == null)
                    {
                        throw new ImageFormatException ("Input stream is not a supported format.");
                    }
                    MemoryStream memoryStream = new MemoryStream ();
                    fileStream.CopyTo (memoryStream);
                    memoryStream.Position = 0;
                    this.Image = format.Load (memoryStream);
                    this.CurrentBitDepth = Image.GetPixelFormatSize (this.Image.PixelFormat);
                    this.InputStream = memoryStream;
                    format.Quality = DefaultQuality;
                    format.IsIndexed = FormatUtilities.IsIndexed (this.Image);
                    this.backupFormat = format;
                    this.CurrentImageFormat = format;
                    foreach (PropertyItem propertyItem in this.Image.PropertyItems)
                    {
                        this.ExifPropertyItems [propertyItem.Id] = propertyItem;
                    }
                    this.backupExifPropertyItems = this.ExifPropertyItems;
                    IAnimatedImageFormat imageFormat = this.CurrentImageFormat as IAnimatedImageFormat;
                    if (imageFormat! = null)
                    {
                        imageFormat.AnimationProcessMode = this.AnimationProcessMode;
                    }
                    Image formatted = this.Image.Copy (this.AnimationProcessMode);
                    this.Image.Dispose ();
                    this.Image = formatted;
                    this.ShouldProcess = true;
                }
            }
            else
            {
                throw new FileNotFoundException (imagePath);
            }
            return this;
        }
   This method is used to load the image to be processed. Always call this method first. This method has 4 overloaded versions, and the received parameters are string, byte [], Image, and Stream respectively. The FormatUtilities.GetFormat (fileStream) method gets the correct ISupportedImageFormat from the given stream. When operating on the picture data stream, the picture stream data will be copied first. format.Load (memoryStream) sets our image to a memory stream value. After an operation is performed on the image data stream, Image.Copy (this.AnimationProcessMode) is called to ensure that the image is the most effective format.

   2.ImageFactoryExtensions.AutoProcess ()
 internal static ImageFactory AutoProcess (this ImageFactory factory, IWebGraphicsProcessor [] graphicsProcessors)
        {
            if (factory.ShouldProcess)
            {
                foreach (IWebGrap
hicsProcessor graphicsProcessor in graphicsProcessors)
                {
                    factory.CurrentImageFormat.ApplyProcessor (graphicsProcessor.Processor.ProcessImage, factory);
                    IDisposable disposable = graphicsProcessor.Processor.DynamicParameter as IDisposable;
                    disposable? .Dispose ();
                }
            }
            return factory;
        }
     The ImageFactoryExtensions class is an extension class of the ImageFactory class, mainly to extend Web projects. The AutoProcess () method automatically processes image files based on any query string parameters added to the image path. The graphicsProcessors parameter indicates the graphics processor array to be applied. graphicsProcessor.Processor.DynamicParameter as IDisposable opens the dynamic parameter and handles any type that requires it.

   3.ImageProcessingModule.SetHeaders ()
 public static void SetHeaders (HttpContext context, int maxDays)
        {
            object responseTypeObject = context.Items [CachedResponseTypeKey];
            object dependencyFileObject = context.Items [CachedResponseFileDependency];
            string responseType = responseTypeObject as string;
            string [] dependencyFiles = dependencyFileObject as string [];
            SetHeaders (context, responseType, dependencyFiles, maxDays);
        }
     In the Web extension, the ImageProcessingModule class is more important, processing any image request in the Web application. The SetHeaders () method enables browsers and servers to save output in their caches, thereby improving performance. This method accepts two parameters. The context represents the requested http message object, and the HttpContext object references the internal server object. The maxDays parameter indicates the maximum number of days to store pictures in the browser cache.

4. Summary
   To be honest, this author likes the coding style, the code introduction is clear, there is not so much pretending writing, and it will not change the readability of the code in order to use some writing. For this series of components, I will write about it as soon as possible. You can use this to learn about some components that you need to understand and use in depth. You can view the source code yourself and expand accordingly. After writing this, it was already two o'clock in the morning and gave me a compliment. No matter what I wrote, I felt that I was still dedicated.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.