. Net image thumbnail upload general method

Posted by sinter4911 on Tue, 21 Jan 2020 17:40:01 +0100

In daily development, we often encounter the demand of uploading pictures. Especially in the development of mall system, if the high-definition original picture is used for the display of commodity list pictures, because the high-definition original picture is relatively large, the loading time of the original picture will be greatly increased, which directly leads to poor system performance, bad user experience, and high concurrency, which directly hangs up. At this time, when uploading pictures in the background , it is necessary to compress the original HD image to generate high-quality thumbnails. Then reading the thumbnails in the commodity list can greatly reduce the loading time and play a role of performance optimization. Of course, the original HD image must be used when the commodity details!

The following code can be used in actual development to compress pictures with high quality. If you don't say much, paste the code below:

 

         /// <summary>
        /// Generate thumbnail or quality compression
        /// </summary>
        /// <param name="sourcePath">Source map path (physical path)</param>
        /// <param name="targetPath">Thumbnail path (physical path)</param>
        /// <param name="width">Thumbnail width, not thumbnail if width is 0</param>
        /// <param name="height">Thumbnail height, not thumbnail if height is 0</param>
        /// <param name="mode">How thumbnails are generated,The default is empty.,If it is empty, the height and width will not be reduced[HW Specifies the height width scale (no deformation); W Specify the width and height in proportion; H Specify the height and width in proportion; CUT Specified height width reduction (no deformation)]</param>  
        /// <param name="flag">Compression quality (smaller number, higher compression ratio) 1-100</param>
        /// <param name="size">Maximum size of compressed picture,0 For unlimited size</param>
        public static void MakeThumbnail(string sourcePath, string targetPath, int width = 0, int height = 0, string mode = "", int flag = 100, int size = 0)
        {
            Image sourceImage = null;
            Image bitmap = null;
            Graphics g = null;
            EncoderParameters ep = null;
            EncoderParameter eParam = null;
            try
            {
                sourceImage = Image.FromFile(sourcePath);

                int toWidth = 0;
                if (width > 0)
                {
                    toWidth = width;
                }
                else
                {
                    toWidth = sourceImage.Width;
                }

                int toHeight = 0;
                if (height > 0)
                {
                    toHeight = height;
                }
                else
                {
                    toHeight = sourceImage.Height;
                }

                int x = 0;
                int y = 0;
                int ow = sourceImage.Width;
                int oh = sourceImage.Height;

                if (width > 0 && height > 0 && !string.IsNullOrWhiteSpace(mode))
                {
                    switch (mode.ToUpper())
                    {
                        case "HW"://Specify height width scaling (no deformation)
                            int tempheight = sourceImage.Height * width / sourceImage.Width;
                            if (tempheight > height)
                            {
                                toWidth = sourceImage.Width * height / sourceImage.Height;
                            }
                            else
                            {
                                toHeight = sourceImage.Height * width / sourceImage.Width;
                            }
                            break;
                        case "W"://Specify width, height to scale                    
                            toHeight = sourceImage.Height * width / sourceImage.Width;
                            break;
                        case "H"://Specify height, width to scale
                            toWidth = sourceImage.Width * height / sourceImage.Height;
                            break;
                        case "CUT"://Specified height width reduction (no deformation)                
                            if ((double)sourceImage.Width / (double)sourceImage.Height > (double)toWidth / (double)toHeight)
                            {
                                oh = sourceImage.Height;
                                ow = sourceImage.Height * toWidth / toHeight;
                                y = 0;
                                x = (sourceImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = sourceImage.Width;
                                oh = sourceImage.Width * height / toWidth;
                                x = 0;
                                y = (sourceImage.Height - oh) / 2;
                            }
                            break;
                    }
                }

                //Build a new one. bmp picture
                bitmap = new Bitmap(toWidth, toHeight);

                //Create a new palette
                g = Graphics.FromImage(bitmap);

                g.CompositingQuality = CompositingQuality.HighQuality;

                //Set up high quality interpolation method
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //Set high quality,Low speed presents smoothness
                g.SmoothingMode = SmoothingMode.HighQuality;

                //Empty canvas and fill with transparent background color
                g.Clear(Color.Transparent);

                //Draws the specified part of the original picture at the specified location and at the specified size
                g.DrawImage(sourceImage, new Rectangle(0, 0, toWidth, toHeight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

                //The following code sets the compression quality when saving pictures
                ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0] = flag;//Set compression scale 1-100
                eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//Get the information of image encoder
                ImageCodecInfo jpegICIinfo = null;
                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[i];
                        break;
                    }
                }

                if (jpegICIinfo != null)
                {
                    bitmap.Save(targetPath, jpegICIinfo, ep);
                    FileInfo fiTarget = new FileInfo(targetPath);
                    if (size > 0 && fiTarget.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        MakeThumbnail(sourcePath, targetPath, width, height, mode, flag, size);
                    }
                }
                else
                {
                    //with jpg Format save thumbnail
                    bitmap.Save(targetPath, ImageFormat.Jpeg);
                }


            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sourceImage != null)
                {
                    sourceImage.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (g != null)
                {
                    g.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (eParam != null)
                {
                    eParam.Dispose();
                }
            }
        }

Topics: ASP.NET