asp. net generate thumbnail sample method to share

  • 2020-10-23 20:04:42
  • OfStack

When doing the site, we often encounter the function of generating thumbnails, because different situations may need to be used for different sizes of thumbnails.

The images generated in this article are all squares, and only the thumbnail of the square can ensure the image is clear enough.

When I say the square here is first compressed proportionally, then I add a fixed white base and then I center it.

Code:

New outputimg ashx


// Resize image 
private static Size NewSize(int maxWidth, int maxHeight, int Width, int Height)
        {
            double w = 0.0;
            double h = 0.0;
            double sw = Convert.ToDouble(Width);
            double sh = Convert.ToDouble(Height);
            double mw = Convert.ToDouble(maxWidth);
            double mh = Convert.ToDouble(maxHeight);
            if (sw < mw && sh < mh)// if maxWidth and maxHeight Larger than the source image, the length and height of the thumbnail remain the same 
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = maxWidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = maxHeight;
                w = (h * sw) / sh;
            }
            return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }


// Generate thumbnails 
public static void SendSmallImage(string filename, string newfile, int maxHeight, int maxWidth, string mode)
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(filename);// Information about the source image 
            System.Drawing.Imaging.ImageFormat thisformat = img.RawFormat; // Format of the source image 
            Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height); // Returns the adjusted image Width with Height
            Bitmap outBmp = new Bitmap(maxWidth, maxHeight);
            Graphics g = Graphics.FromImage(outBmp);
            // Set the paint quality of the canvas 
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.Clear(Color.White);
            g.DrawImage(img, new Rectangle(((maxWidth - newSize.Width) / 2), ((maxHeight - newSize.Height) / 2), newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            g.Dispose();
            // The following code sets the compression quality when saving the image 
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            // Gets information that contains information about the built-in image codec ImageCodecInfo Object. 
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];// Set up the jpeg coding 
                    break;
                }
            }
            if (jpegICI != null)
            {
                outBmp.Save(newfile, jpegICI, encoderParams);
            }
            else
            {
                outBmp.Save(newfile, thisformat);
            }
            img.Dispose();
            outBmp.Dispose();
        }

Output picture:


// The output image 
        public static void OutPutImg(string imgFilePath)
        {
            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(imgFilePath), FileMode.Open, FileAccess.Read);
            DateTime contentModified = System.IO.File.GetLastWriteTime(HttpContext.Current.Server.MapPath(imgFilePath));
            if (IsClientCached(contentModified))
            {
                HttpContext.Current.Response.StatusCode = 304;
                HttpContext.Current.Response.SuppressContent = true;
            }
            else
            {
                byte[] mydata = new byte[fs.Length];
                int Length = Convert.ToInt32(fs.Length);
                fs.Read(mydata, 0, Length);
                fs.Close();
                HttpContext.Current.Response.OutputStream.Write(mydata, 0, Length);
                HttpContext.Current.Response.ContentType = "image/jpeg";
                HttpContext.Current.Response.End();
                HttpContext.Current.Response.Cache.SetETagFromFileDependencies();
                HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(true);
                HttpContext.Current.Response.Cache.SetLastModified(contentModified);
            }
        }


//outpuimg.ashx?src=/images/weimeidesc/8af30049-797e-4eb4-8a54-cc4de47c1694.jpg!100x100.jpg
        public void ProcessRequest(HttpContext context)
        {
            // Get photo 
            string imgUrl = context.Request.QueryString["src"];
            string trueFilePath = imgUrl.Split('!')[0];
            // Get image size 
            int width = Convert.ToInt32(imgUrl.Split('!')[1].Replace(".jpg", "").Split('x')[0]);
            int height = Convert.ToInt32(imgUrl.Split('!')[1].Replace(".jpg", "").Split('x')[1]);

            // The image already exists in the direct output 
            if (File.Exists(context.Server.MapPath("~/" + imgUrl)))
            {
                OutPutImg("~/"+imgUrl);
            }
            else
            {
                if (!string.IsNullOrEmpty(imgUrl) && File.Exists(context.Server.MapPath("~/" + trueFilePath)))
                {
                    Image originalImage = System.Drawing.Image.FromFile(context.Server.MapPath("~/" + trueFilePath));
                    var newBitmap = new Bitmap(originalImage);
                    // Generate and save the corresponding small image 
                    SendSmallImage(context.Server.MapPath("~/" + trueFilePath),context.Server.MapPath("~/" + imgUrl), width, height, "meiyouyisi");
                    // The output 
                    OutPutImg("~/" + imgUrl);
                }
                else// If the picture doesn't exist   Output default image 
                {
                    //OutPutImg(imgUrl);
                }
            }
        }


Related articles: