Generating image thumbnails in ASP.NET?

前端 未结 7 1539
再見小時候
再見小時候 2020-12-08 22:02

What is the fastest and more reliable way of generating thumbnails in .NET? I need to get any image, compress it in JPEG and resize it.

I\'ve seen several examples w

7条回答
  •  感情败类
    2020-12-08 22:36

    This has done me fine for years:

    public static void CreateThumbnail(string filename, int desiredWidth, int desiredHeight, string outFilename)
    {
        using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
        {
            float widthRatio = (float)img.Width / (float)desiredWidth;
            float heightRatio = (float)img.Height / (float)desiredHeight;
            // Resize to the greatest ratio
            float ratio = heightRatio > widthRatio ? heightRatio : widthRatio;
            int newWidth = Convert.ToInt32(Math.Floor((float)img.Width / ratio));
            int newHeight = Convert.ToInt32(Math.Floor((float)img.Height / ratio));
            using (System.Drawing.Image thumb = img.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailImageAbortCallback), IntPtr.Zero))
            {
                thumb.Save(outFilename, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
    
    public static bool ThumbnailImageAbortCallback()
    {
        return true;
    }
    

提交回复
热议问题