ASP.NET C#上传图片生成缩略图

资料原自网络,本人小小修改一下,备注以后使用。

CS代码 

ExpandedBlockStart.gif 代码
  1    ///   <summary>  
  2       ///  asp.net上传图片并生成缩略图 
  3       ///   </summary>  
  4       ///   <param name="upImage"> HtmlInputFile控件 </param>  
  5       ///   <param name="sSavePath"> 保存的路径,些为相对服务器路径的下的文件夹 </param>  
  6       ///   <param name="sThumbExtension"> 缩略图的thumb </param>  
  7       ///   <param name="intThumbWidth"> 生成缩略图的宽度 </param>  
  8       ///   <param name="intThumbHeight"> 生成缩略图的高度 </param>  
  9       ///   <returns> 缩略图名称 </returns>  
 10       public   string  UpLoadImage(HtmlInputFile upImage,  string  sSavePath,  string  sThumbExtension,  int  intThumbWidth,  int  intThumbHeight)
 11      {
 12           #region
 13           #region
 14           string  sThumbFile  =   "" ;
 15           string  sFilename  =   "" ;
 16           if  (txtTitle.Text.Trim().Length  >   0 )
 17          {
 18          }
 19           else
 20          {
 21              Jscript.Alert( " 标题不能为空 " );
 22               return   " 标题不能为空 " ;
 23          }
 24          School.Model.BlogUserPic bumodel  =   new  School.Model.BlogUserPic();
 25          School.BLL.BlogUserPic buBll  =   new  School.BLL.BlogUserPic();
 26 
 27           // 获取用户ID
 28          EncryptStr Encry  =   new  EncryptStr();
 29          userID  =  Encry.Decrypt(HttpContext.Current.Request.Cookies[ " SchoolStudent " ][ " UserID " ].ToString());
 30 
 31           // 设置添加信息
 32          bumodel.PicTitle  =  Utils.ChkSQL( this .txtTitle.Text.Trim().ToString());
 33          bumodel.PicDesc  =  Utils.ChkSQL( this .txtPicDesc.Text.Trim().ToString());
 34          bumodel.addTime  =  DateTime.Now;
 35          bumodel.UserId  =  Utils.StrToInt(userID,  0 );
 36          bumodel.uploadIP  =  DNTRequest.GetIP();
 37          bumodel.IsDel  =   0 ;
 38          bumodel.IsCheck  =   1 ;
 39           #endregion
 40           #region
 41           if  (upImage.PostedFile  !=   null )
 42          {
 43              HttpPostedFile myFile  =  upImage.PostedFile;
 44               int  nFileLen  =  myFile.ContentLength;
 45               if  (nFileLen  ==   0 )
 46              {
 47                  Jscript.Alert( " 没有选择上传图片 " );
 48                   return   " 没有选择上传图片 " ;
 49              }
 50               if  (nFileLen  >   2097152 )
 51              {
 52                  Jscript.Alert( " 上传图片不能大于2MB " );
 53                   return   " 上传图片不能大于2MB " ;
 54              }
 55               // 获取upImage选择文件的扩展名
 56               string  extendName  =  System.IO.Path.GetExtension(myFile.FileName).ToLower();
 57               // 判断是否为图片格式
 58               if  (extendName  !=   " .jpg "   &&  extendName  !=   " .jpge "   &&  extendName  !=   " .gif "   &&  extendName  !=   " .bmp "   &&  extendName  !=   " .png " )
 59              {
 60                  Jscript.Alert( " 图片格式不正确 " );
 61                   return   " 图片格式不正确 " ;
 62              }
 63               byte [] myData  =   new  Byte[nFileLen];
 64              myFile.InputStream.Read(myData,  0 , nFileLen);
 65              sFilename  =  System.IO.Path.GetFileName(myFile.FileName);
 66               int  file_append  =   0 ;
 67               // 检查当前文件夹下是否有同名图片,有则在文件名+1
 68               while  (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath  +  sFilename)))
 69              {
 70                  file_append ++ ;
 71                  sFilename  =  System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
 72                +  file_append.ToString()  +  extendName;
 73              }
 74              System.IO.FileStream newFile  =   new  System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath(sSavePath  +  sFilename),
 75                  System.IO.FileMode.Create, System.IO.FileAccess.Write);
 76              newFile.Write(myData,  0 , myData.Length);
 77              newFile.Close();
 78               // 以上为上传原图
 79               #region
 80               try
 81              {
 82                   // 原图加载
 83                   using  (System.Drawing.Image sourceImage  =  System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(sSavePath  +  sFilename)))
 84                  {
 85                       // 原图宽度和高度
 86                       int  width  =  sourceImage.Width;
 87                       int  height  =  sourceImage.Height;
 88                       int  smallWidth;
 89                       int  smallHeight;
 90                       // 获取第一张绘制图片的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高)
 91                       if  ((( decimal )width)  /  height  <=  (( decimal )intThumbWidth)  /  intThumbHeight)
 92                      {
 93                          smallWidth  =  intThumbWidth;
 94                          smallHeight  =  intThumbWidth  *  height  /  width;
 95                      }
 96                       else
 97                      {
 98                          smallWidth  =  intThumbHeight  *  width  /  height;
 99                          smallHeight  =  intThumbHeight;
100                      }
101 
102                       // 判断缩略图在当前文件夹下是否同名称文件存在
103                      file_append  =   0 ;
104                      sThumbFile  =  sThumbExtension  +  System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)  +  extendName;
105                       while  (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath  +  sThumbFile)))
106                      {
107                          file_append ++ ;
108                          sThumbFile  =  sThumbExtension  +  System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)  +  file_append.ToString()  +  extendName;
109                      }
110 
111                       // 缩略图保存的绝对路径
112                       string  smallImagePath  =  Server.MapPath(sSavePath)  +  sThumbFile;
113                       // System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
114                       // bumodel.PicUrl = Server.MapPath(smallImagePath);
115                      bumodel.PicUrl  =   " /UploadBlogPhoto/ "   +  userID  +   " / "   +  sThumbFile; // 压缩过的图片
116                       // smallImagePath;
117                       // 业务层 增加方法 bumodel是model
118                      buBll.Add(bumodel); // 添加相片
119                      Response.Write( " <script language='JavaScript'>alert('添加相片成功');window.location='BlogUserPic.aspx?userID= "   +  userID  +   " ';</script> " );
120                       // Response.End();
121                       // 新建一个图板,以最小等比例压缩大小绘制原图
122                       using  (System.Drawing.Image bitmap  =   new  System.Drawing.Bitmap(smallWidth, smallHeight))
123                      {
124                           // 绘制中间图
125                           using  (System.Drawing.Graphics g  =  System.Drawing.Graphics.FromImage(bitmap))
126                          {
127                               // 高清,平滑
128                              g.InterpolationMode  =  System.Drawing.Drawing2D.InterpolationMode.High;
129                              g.SmoothingMode  =  System.Drawing.Drawing2D.SmoothingMode.HighQuality;
130                              g.Clear(System.Drawing.Color.White);
131                              g.DrawImage(
132                                  sourceImage,  new  System.Drawing.Rectangle( 0 0 , smallWidth, smallHeight),
133                                   new  System.Drawing.Rectangle( 0 0 , width, height), System.Drawing.GraphicsUnit.Pixel);
134                          }
135                           // 新建一个图板,以缩略图大小绘制中间图
136                           using  (System.Drawing.Image bitmap1  =   new  System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
137                          {
138                               // 绘制缩略图
139                               using  (System.Drawing.Graphics g  =  System.Drawing.Graphics.FromImage(bitmap1))
140                              {
141                                   // 高清,平滑
142                                  g.InterpolationMode  =  System.Drawing.Drawing2D.InterpolationMode.High;
143                                  g.SmoothingMode  =  System.Drawing.Drawing2D.SmoothingMode.HighQuality;
144                                  g.Clear(System.Drawing.Color.White);
145                                   int  lwidth  =  (smallWidth  -  intThumbHeight)  /   2 ;
146                                   int  bheight  =  (smallHeight  -  intThumbHeight)  /   2 ;
147                                  g.DrawImage(bitmap,  new  Rectangle( 0 0 , intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
148                                  g.Dispose();
149                                  bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
150                              }
151                          }
152                      }
153 
154                  }
155              }
156 
157               catch
158              {
159                   // 出错则删除 
160                  System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath  +  sFilename));
161                  Jscript.Alert( " 图片格式不正确 " );
162                   return   " 图片格式不正确 " ;
163              }
164               #endregion
165               // 返回缩略图名称 
166               return  sThumbFile;
167          }
168           #endregion
169          Jscript.Alert( " 没有选择图片 " );
170           return   " 没有选择图片 " ;
171           #endregion
172      }

 

CS button控件事件

 1     ///   <summary>
 2       ///  上传图片事件
 3       ///   </summary>
 4       ///   <param name="sender"> sender </param>
 5       ///   <param name="e"> e </param>
 6       protected   void  btnSmbit_Click( object  sender, EventArgs e)
 7      {
 8           // 获取用户ID
 9          EncryptStr Encry  =   new  EncryptStr();
10          userID  =  Encry.Decrypt(HttpContext.Current.Request.Cookies[ " SchoolStudent " ][ " UserID "        ].ToString());
11           // 我们是根据用户ID生成一个文件夹,保存到单独的文件夹
12           this .UpLoadImage( this .File1,  " ../UploadBlogPhoto/ "   +  userID  +   " / " " thumb_ " 600 600 );
13      }

 

 前台代码

    <td>

                添加相片:

                <input id="File1" runat="server" type="file" />        

       <asp:Button ID="btnSmbit" runat="server" Text="提交" OnClick="btnSmbit_Click" /> 

            </td>

 

转载于:https://www.cnblogs.com/LeeYongze/archive/2010/05/27/1745206.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值