2010年6月20日 星期日

ASP.NET C# 上傳圖檔並產生縮圖

在縮圖前就先計算好維持比例的縮圖尺寸,例如 800x600 要縮成 200x200 時,實際上應該縮成 200x150 ,於是下參數就下 200x150 ,修改後的原始碼(.CS):
using System;
using System.Drawing;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UploadPicture01 : System.Web.UI.Page
{
// 設定縮圖後的檔案存放路徑
private const string savePath = @"C:\Inetpub\wwwroot\200x200\";

// 設定暫存路徑
private const string tempPath = @"C:\Inetpub\wwwroot\temp\";

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string tempName = tempPath + FileUpload1.FileName;
string imageName = savePath + FileUpload1.FileName;

// 儲存暫存檔
FileUpload1.SaveAs(tempName);

// System.Web.UI.WebControls 與 System.Drawing 同時擁有 Image 類別
// 所以以下程式碼明確指定要使用的是 System.Drawing.Image

System.Drawing.Image.GetThumbnailImageAbort callBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap image = new Bitmap(tempName);

// 計算維持比例的縮圖大小
int[] thumbnailScale = getThumbnailImageScale(200, 200, image.Width, image.Height);

// 產生縮圖
System.Drawing.Image smallImage =
image.GetThumbnailImage(thumbnailScale[0], thumbnailScale[1], callBack, IntPtr.Zero);

// 將縮圖存檔
smallImage.Save(imageName);

// 釋放並刪除暫存檔
image.Dispose();
System.IO.File.Delete(tempName);
}
}

// 計算維持比例的縮圖大小
private int[] getThumbnailImageScale(int maxWidth, int maxHeight, int oldWidth, int oldHeight)
{
int[] result = new int[] { 0, 0 };
float widthDividend, heightDividend, commonDividend;

widthDividend = (float)oldWidth / (float)maxWidth;
heightDividend = (float)oldHeight / (float)maxHeight;

commonDividend = (heightDividend > widthDividend) ? heightDividend : widthDividend;
result[0] = (int)(oldWidth / commonDividend);
result[1] = (int)(oldHeight / commonDividend);

return result;
}

private bool ThumbnailCallback()
{
return false;
}
}