上传图片并生成缩略图

<formid="Form1"method="post"runat="server"enctype="multipart/form-data">
<tableid="Table1"cellpadding="1"cellspacing="1"width568border="1">
<tr>
<td>
<asp:LabelID="Label1"Runat="server">要上传的图片</asp:Label>
</td>
<td>
<inputid="upImage"type="file"name="File1"runat="server"></td>
<td><asp:ButtonID="btnUp"Runat="server"Text="上传并生成缩图"></asp:Button></td>
</tr>
<tr>
<td><asp:LabelID="Label2"Runat="server">原图片</asp:Label></td>
<tdalign="center"colspan="2"><asp:ImageID="imageSource"Runat="server"></asp:Image>
</td>
</tr>
<tr>
<td><asp:LabelID="Label3"Runat="server">缩图</asp:Label></td>
<tdalign="center"colspan="2">
<asp:ImageID="imageSmall"Runat="server"></asp:Image></td>
</tr>
</table>
</form>

后台:

publicSystem.Drawing.Imageimage,newimage;//定义
protectedstringimagePath;
protectedstringimageType;
protectedstringimageName;
//提供一个回调方法,用于确定Image对象在执行生成缩图操作时河时提前取消执行
//如果此方法确定GetThumbnailImage方法应该提前停此执行,返回true否则返回false
protectedSystem.Drawing.Image.GetThumbnailImageAbortcallb=null;
privatevoidbtnUp_Click(objectsender,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("上传失败");
}

}

}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值