ASP.NET Image Uploading with Resizing

當你使用 ASP.NET 建立上傳圖檔的應用程式時,除了要決定寫入檔案系統或是儲存到資料庫外,你可能還會需要依照原圖的尺寸比例來調整圖片的大小,以符合系統的需求。本文範例程式碼將透過 Image 及 Bitmap 類別,對上傳的原圖進行比例縮放,並以 JPEG 圖檔格式存儲。

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Drawing=System.Drawing" %>
<script runat="server">
const string _uploadFolder = "~/images/";
const int _maxThumbWidth = 100;

protected void uxUpload_Click(object sender, EventArgs e)
{
if (uxImageFile.HasFile)
{
if (IsValidImage(uxImageFile.FileName))
{
string thumbPath = _uploadFolder +
Path.ChangeExtension(Path.GetRandomFileName(), ".jpg");

using (Drawing::Image image =
Drawing::Image.FromStream(uxImageFile.PostedFile.InputStream))
{
decimal sizeRatio = ((decimal)image.Height / image.Width);
int thumbWidth = _maxThumbWidth;
int thumbHeight = decimal.ToInt32(sizeRatio * thumbWidth);

using (Drawing::Bitmap bitmap =
new Drawing::Bitmap(image, new Drawing::Size(thumbWidth, thumbHeight)))
{
bitmap.Save(Server.MapPath(thumbPath),
Drawing::Imaging.ImageFormat.Jpeg);
}
}
uxThumbImage.ImageUrl = thumbPath;
}
else
{
// This type of file is not allowed.
uxThumbImage.ImageUrl = string.Empty;
}
}
}

public bool IsValidImage(string path)
{
return Regex.IsMatch(path, @"(.*?)\.(gif|jpg|jpeg|png)$", RegexOptions.IgnoreCase);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Image Upload and Resize</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="uxImageFile" runat="server" /><br/>
<asp:Button ID="uxUpload" runat="server"
Text="Upload" onclick="uxUpload_Click" /><br/>
<asp:Image ID="uxThumbImage" runat="server"
onerror="javascript:this.style.display='none';" />
</div>
</form>
</body>
</html>

參考資料:
Create High Quality Thumbnail - Resize Image Dynamically - ASP .Net C# Code


Share/Save/Bookmark

0 comments :: ASP.NET Image Uploading with Resizing

張貼留言