上傳圖片時等比縮放的一個小小算法
阿新 • • 發佈:2017-05-21
lba sim image 委托 fromfile tps 獲取 head 引用
protected void Button1_Click(object sender, EventArgs e) { int width = 300, height = 300;//生成縮略圖時定義一個最大的寬和高 System.Drawing.Image img = System.Drawing.Image.FromFile("d:/test.jpg"); int swidth =img.Width;//源圖片的寬 int sheight = img.Height;//源圖片的高 var info = newSImg { width = swidth, height = sheight }; info.GetHW(width, height, info); //得到縮放後的寬和高 int w = info.width; int h = info.height; //獲取縮略圖 System.Drawing.Image smallimg = img.GetThumbnailImage(w, h, newSystem.Drawing.Image.GetThumbnailImageAbort(() => { return false; }), IntPtr.Zero);
} public class SImg { public int width { get; set; } public int height { get; set; } public void GetHW(int width, int height, SImg img) {//如果寬和高任意一個超過定義的寬和高 執行等比 if (img.width > width || img.height > height) { img.width = img.width / 2; img.height = img.height / 2; GetHW(width, height, img); } } }
Image.GetThumbnailImage 方法
public Image GetThumbnailImage ( int thumbWidth, int thumbHeight, GetThumbnailImageAbort callback, IntPtr callbackData )
參數
- thumbWidth
-
請求的縮略圖的寬度(以像素為單位)。
- thumbHeight
-
請求的縮略圖的高度(以像素為單位)。
- callback
-
一個 Image.GetThumbnailImageAbort 委托。在 GDI+ 1.0 版中不使用此委托。即便如此,也必須創建一個委托並在該參數中傳遞對此委托的引用。
- callbackData
-
必須為 Zero。
上傳圖片時等比縮放的一個小小算法