How to resize an Image C#

前端 未结 17 2647
暗喜
暗喜 2020-11-21 22:28

As Size, Width and Height are Get() properties of System.Drawing.Image;
How can I resize an Image object

17条回答
  •  萌比男神i
    2020-11-21 23:03

    Resize and save an image to fit under width and height like a canvas keeping image proportional

    using System;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    
    namespace Infra.Files
    {
        public static class GenerateThumb
        {
            /// 
            /// Resize and save an image to fit under width and height like a canvas keeping things proportional
            /// 
            /// 
            /// 
            /// 
            /// 
            public static void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight)
            {
                Bitmap srcBmp = new Bitmap(originalImagePath);
                float ratio = 1;
                float minSize = Math.Min(newHeight, newHeight);
    
                if (srcBmp.Width > srcBmp.Height)
                {
                    ratio = minSize / (float)srcBmp.Width;
                }
                else
                {
                    ratio = minSize / (float)srcBmp.Height;
                }
    
                SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio);
                Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height);
    
                using (Graphics graphics = Graphics.FromImage(target))
                {
                    graphics.CompositingQuality = CompositingQuality.HighSpeed;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.CompositingMode = CompositingMode.SourceCopy;
                    graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
    
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        target.Save(thumbImagePath);
                    }
                }
            }
        }
    }
    

提交回复
热议问题