[C#] 圖片縮圖

System.Drawing namespace 提供對 GDI+ 基本繪圖功能的存取,可以方便處理圖片的操作,下面是一個處理圖片縮圖的範例:

//using System.Drawing;

var image = Image.FromFile(@"D:\001.jpg");

int width = 120, height = 100;
float targetRatio = (float)width / (float)height;
float imageRatio = (float)image.Width / (float)image.Height;

if(imageRatio < targetRatio)
    width = Math.Max(1, height * image.Width / image.Height);
    height = Math.Max(1, width * image.Height / image.Width); 

var thumbnail = image.GetThumbnailImage(width, height, null, IntPtr.Zero);


這個方式可以容易的做到圖片縮圖,但使用這個方式會很佔用記憶體,在處理尺寸大的圖片時有可能會出現 out of memory,而且在 MSDN 有以下的警示:
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

0 回應: