上传图片并生成缩略图

< form id ="Form1" method ="post" runat ="server" enctype ="multipart/form-data" >
< table id ="Table1" cellpadding ="1" cellspacing ="1" width568border ="1" >
< tr >
< td >
< asp:Label ID ="Label1" Runat ="server" > 要上传的图片 </ asp:Label >
</ td >
< td >
< input id ="upImage" type ="file" name ="File1" runat ="server" ></ td >
< td >< asp:Button ID ="btnUp" Runat ="server" Text ="上传并生成缩图" ></ asp:Button ></ td >
</ tr >
< tr >
< td >< asp:Label ID ="Label2" Runat ="server" > 原图片 </ asp:Label ></ td >
< td 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 >
</ form >

后台:

public System.Drawing.Imageimage,newimage; // 定义
protected string imagePath;
protected string imageType;
protected string imageName;
// 提供一个回调方法,用于确定Image对象在执行生成缩图操作时河时提前取消执行
// 如果此方法确定GetThumbnailImage方法应该提前停此执行,返回true否则返回false
protected System.Drawing.Image.GetThumbnailImageAbortcallb = null ;
private void btnUp_Click( object sender,System.EventArgse)
... {
stringmPath;
if(""!=upImage.PostedFile.FileName)
...{
imagePath
=upImage.PostedFile.FileName;
//取的图片类型
imageType=imagePath.Substring(imagePath.LastIndexOf(".")+1);
//取得图片名称
imageName=imagePath.Substring(imagePath.IndexOf("/")+1);
if("jpg"!=imageType&&"gif"!=imageType)
...{
Response.Write(
"<scriptlaguage='javascript'>alert('请选择jpg和gif图片');</script>");
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(300,300,callb,newSystem.IntPtr());
//把缩图保存到指定的虚拟路径
newimage.Save(Server.MapPath("upFile")+"/small"+imageName);
//释放image对象占用的资源
image.Dispose();
newimage.Dispose();

imageSmall.ImageUrl
="upFile/"+"small"+imageName;
this.Response.Write("上传成功");

}

catch
...{
this.Response.Write("上传失败");
}

}

}


}


你可能感兴趣的:(缩略图)