using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;




/**//// <summary>
/// 上传图片后并把图片处理成适当大小,是横图片则处理成宽为maxSize,
/// 是竖图片的处理成高为maxHSize,比例小于maxSize或maxHSize则不作处理
/// </summary>
/// <param name="page">页面对象,为了在方法中可以使用Page对象</param>
/// <param name="FilePic">上传文件框,用于选择图片</param>
/// <param name="imgLogo">image控件,用于显示上传后的图片</param>
/// <param name="txtPath">text文本框,用来保存上传图片的路径</param>
/// <param name="maxSize">最大图片宽度</param>
/// <param name="maxHSize">最大图片高度</param>
/// <param name="srcpath">图片的保存路径</param>
public static void UploadImage(System.Web.UI.Page page,ref System.Web.UI.HtmlControls.HtmlInputFile FilePic,ref System.Web.UI.WebControls.Image imgLogo,ref System.Web.UI.WebControls.TextBox txtPath,int maxSize,int maxHSize,string srcpath)

{
if(FilePic.PostedFile.FileName!=null)

{
try

{
string dtime=DateTime.Now.ToString("yyMMddHHmmss");
if(!(FilePic.PostedFile.ContentLength>0))

{
page.Response.Write("<script> {alert(\'请选择要上传的图片!\');}<"+"/script>");
page.Response.Write("<script>history.go(-1)<"+"/script>");
}
else

{
//int maxSize=150;//图片的长宽最大像素
string strtype=FilePic.PostedFile.FileName.Substring(FilePic.PostedFile.FileName.LastIndexOf('.'));
//string srcpath="UploadFiles/";//存储图片的文件夹路径
string path=page.Server.MapPath(srcpath+dtime+strtype);
string imgname=dtime+strtype;
System.Drawing.Image bigimage=System.Drawing.Image.FromStream(FilePic.PostedFile.InputStream);
System.Drawing.Bitmap output=new System.Drawing.Bitmap(bigimage);
decimal width=bigimage.Width;
decimal height=bigimage.Height;
int newwidth,newheight;
if(width>=height)

{
if(width>maxSize)

{
newwidth=maxSize;
newheight=(int)(height/width*maxSize);
}
else

{
newwidth=(int)width;
newheight=(int)height;
}
}
else

{
if(height>maxHSize)

{
newheight=maxHSize;
newwidth=(int)(width/height*maxHSize);
}
else

{
newwidth=(int)width;
newheight=(int)height;
}
}
System.Drawing.Image smallimage=output.GetThumbnailImage(newwidth,newheight,null, IntPtr.Zero);
switch(strtype)

{
case ".jpg":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".ico":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.Icon);
break;
case ".bmp":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.MemoryBmp);
break;
case ".png":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.Png);
break;
case ".tif":
smallimage.Save(path,System.Drawing.Imaging.ImageFormat.Tiff);
break;
}
imgLogo.Visible=true;
imgLogo.ImageUrl=srcpath+dtime+strtype;
txtPath.Text=srcpath+dtime+strtype;
}
}
catch(Exception ex)

{
page.Response.Redirect("~/Manage/ErrorPage.aspx?ErrorUrl="
+ YLWeb.Class.WebSystem.RedirectErrorUrl(page.Request.RawUrl)
+ "&ErrorMessage=" + ex.Message.Replace("\n"," "));
}
}
}

posted on
2007-02-07 12:50
mbskys
阅读(
140)
评论()
收藏
举报