<%@ 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
0 comments :: ASP.NET Image Uploading with Resizing
張貼留言