asp.net 保存图片 生成缩略图


利用C#.Net的FileUpload或者HtmlInputFile控件上传文件,首先保存上传文件,然后生产缩略图文件并保存

1、验证并生成文件名

            string strSiteFileName = null;
            string strSiteUrl = this.fu_Site_Img.PostedFile.FileName.Trim(); //取得文件路径
            if (strSiteUrl != "" && strSiteUrl != null)
            {
                string strImgType = strSiteUrl.Substring(strSiteUrl.LastIndexOf(".")); //取得文件扩展名  
                if (strImgType.ToLower() != ".gif" && strImgType.ToLower() != ".jpeg" && strImgType.ToLower() != ".jpg" && strImgType.ToLower() != ".png" && strImgType.ToLower() != ".bmp")
                {
                    throw new Exception("只能保存.gif|.jpg|.jpeg|.png或.bmp格式的图片!");
                }
                if (this.fu_Site_Img.PostedFile.ContentLength > 1024000)
                {
                    throw new Exception("文件大小不能超过1M!");
                }
                Random rd = new Random();
                strSiteFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + rd.Next(100, 999).ToString() + strImgType.ToLower();
            }

2、上传文件

                if (strSiteFileName != null)
                {
                    string strFilePath = Server.MapPath(@"../../NewStyle/corpImage/" + strSiteFileName);
                    HttpPostedFile upfile;
                    upfile = this.fu_Site_Img.PostedFile;

                    //保存原文件
                    upfile.SaveAs(strFilePath);

                    //生成缩略图保存
                    System.Drawing.Image image = System.Drawing.Image.FromStream(upfile.InputStream);
                    int width = image.Width;
                    int height = image.Height;

                    int max = 500;
                    if (width > max || height > max)
                    {
                        try
                        {
                            System.Drawing.Image newPic; //定义新位图对象
                            if (width > height)
                            {
                                newPic = new Bitmap(image, max, height * max / width); //缩放
                            }
                            else
                            {
                                newPic = new Bitmap(image, width * max / height, max); //缩放
                            }
                            newPic.Save(strFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); //将处理后的图片保存成Png文件
                        }
                        catch (System.Exception ex)
                        {
                            throw ex;
                        }
                    }
                }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值