<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
//定义image类的对象
System.Drawing.Image image, newimage;
//图片路径
protected string imagePath;
//图片类型
protected string imageType;
//图片名称
protected string imageName;
//提供一个回调方法,用于确定Image对象在执行生成缩略图操作时何时提前取消执行
//如果此方法确定 GetThumbnailImage 方法应提前停止执行,则返回 true;否则返回 false
System.Drawing.Image.GetThumbnailImageAbort callb = null;
protected void btnUp_Click(object sender, EventArgs e)
{
string mPath;
if ("" != upImage.PostedFile.FileName)
{
imagePath = upImage.PostedFile.FileName;
imageType = imagePath.Substring(imagePath.LastIndexOf(".") + 1);
imageName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1);
if ("jpg" != imageType && "gif" != imageType)
{
return;
}
else
{
try
{
//建立虚拟路径
mPath = Server.MapPath("upFile");
//保存到虚拟路径
upImage.PostedFile.SaveAs(mPath + "\\" + imageName);
//显示原图
imageSource.ImageUrl = "upFile/" + imageName;
//为上传的图片建立引用
image = System.Drawing.Image.FromFile(mPath + "\\" + imageName);
//生成缩略图
newimage = image.GetThumbnailImage(100, 100, callb, new System.IntPtr());
//把缩略图保存到指定的虚拟路径
newimage.Save(Server.MapPath("upFile") + "\\small" + imageName);
//释放image对象占用的资源
image.Dispose();
//释放newimage对象的资源
newimage.Dispose();
//显示缩略图
imageSmall.ImageUrl = "upFile/" + "small" + imageName;
Response.Write("上传成功!");
}
catch
{
Response.Write("上传成功!");
}
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>asp.net上传图片并生成缩略图</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<TABLE id="Table1" style="Z-INDEX: 101; LEFT: 32px; WIDTH: 568px; POSITION: absolute; TOP: 24px; HEIGHT: 336px"
cellSpacing="1" cellPadding="1" width="568" border="1">
<TR>
<TD style="HEIGHT: 16px"><asp:label id="Label1" runat="server">要上传的图片</asp:label></TD>
<TD style="HEIGHT: 16px"><INPUT id="upImage" type="file" name="File1" runat="server"></TD>
<TD style="HEIGHT: 16px"><asp:button id="btnUp" runat="server" Text="上传并生成缩略图" OnClick="btnUp_Click"></asp:button></TD>
</TR>
<TR>
<TD style="HEIGHT: 154px"><asp:label id="Label2" runat="server">原图片</asp:label></TD>
<TD style="HEIGHT: 154px" align="center" colSpan="2"><asp:image id="imageSource" runat="server"></asp:image></TD>
</TR>
<TR>
<TD><asp:label id="Label3" runat="server">缩略图</asp:label></TD>
<TD align="center" colSpan="2"><asp:image id="imageSmall" runat="server"></asp:image></TD>
</TR>
</TABLE>
</div>
</form>
</body>
</html>