C#上传图片并按比例生成缩略图收藏

          /// <summary>
        /// 图片上传,带上缩略图
    /// </summary>
        /// <param name="FileUpload1">上传的控件的ID</param>
        /// <param name="SavePath">保存的路径,相对路径如“/Images/Picture/”,使用配置文件</param>
        /// <param name="refName">返回的文件名,不带路径</param>
        /// <param name="width">缩略图的宽</param>
        /// <param name="height">缩略图的高</param>
        /// <param name="maxLength">图片最大的大小</param>
        /// <returns></returns>

         public    bool  UpLoadImage(HtmlInputFile FileUpload1,  string  SavePath,  ref   string  refName,  int  width,  int  height,  int  maxLength)
         {
            //在转换的时候需求使用系统路径
            SavePath = "~" + SavePath; 
            ///成功状态
            bool ret = true;
            ///上传文件名称组
            string fileNames = string.Empty;
            //上传文件总大小
            int fileLength = 0;
            //图片类型
            string imgType = string.Empty;
            //图片类型集合
            ICollection ic = new string[] { ".gif", ".jpg", ".GIF", ".JPG" };
            ArrayList imgTypes = new ArrayList(ic);

            ///判断上传文件的有效性

            ///检查文件扩展名字

            string name = System.IO.Path.GetFileName(FileUpload1.Value);
            if (name == "")
            {
                ///状态信息
                ret = false;
                refName = "图片不存在";
                return false;
            }

            imgType = System.IO.Path.GetExtension(FileUpload1.Value);
            if (!imgTypes.Contains(imgType))
            {
                ///状态信息
                ret = false;
                refName = "图片格式不对";
                return false;
            }

            fileLength = fileLength + FileUpload1.PostedFile.ContentLength;

            //系统规定大小
            int sysLength = maxLength * 1024;
            if (fileLength > sysLength)
            {
                ///状态信息
                ret = false;
                refName = "图片超过200KB上限!";
                 return false;
            }

            ///图片上传
            try
            {
                string picPath = SavePath;

                string fileName, fileExtension;
                ///上传文件的文件名
                fileName = System.IO.Path.GetFileName(FileUpload1.Value);
                if (fileName != "")
                {
                    ///上传文件的扩展名
                    fileExtension = System.IO.Path.GetExtension(fileName);
                    ///生成新的文件名
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmffff") + fileExtension;
                    ///可根据扩展名字的不同保存到不同的文件夹
                    string date = DateTime.Now.ToString("yyyyMM");
                    picPath = Server.MapPath(picPath + date + "/");
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(picPath);
                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    ///注意:可能要修改您的文件夹的匿名写入权限。
                    FileUpload1.PostedFile.SaveAs(picPath + fileName);
                    refName = date + "/" + fileName;
                    GetThumbnailImage(SavePath , date + "/", fileName, width, height);
                }


            }

            catch 
            {

                ret = false;
                refName = "上传失败!";
                return false;
            }

            return ret;
        }

 

 生成缩略图代码:

 

/// <param name="SavePath">原始路径</param>
        /// <param name="pathDate">添加的月份路径</param>
        /// <param name="picFilePath">保存的文件名</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>

         public   void  GetThumbnailImage( string  SavePath,  string  pathDate, string  picFilePath,  int  width,  int  height)
         {
            //添加small100的前缀大小
       //程序内相对的服务器路径小图片
      string strRelativeSmallPath = SavePath + CommEnum.Pictures_Small100 + pathDate;

            string SmallPath100 = Server.MapPath(strRelativeSmallPath + picFilePath);
            string machpath = Server.MapPath(SavePath + pathDate + picFilePath);
            string isDir = SmallPath100.Substring(0, SmallPath100.LastIndexOf('/'));
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(isDir);
            if (!di.Exists)
            {
                di.Create();
            }

            Bitmap img = new Bitmap(machpath);  //read picture to memory

            int h = img.Height;
            int w = img.Width;
            int ss, os;// source side and objective side
            double temp1, temp2;
            //compute the picture's proportion
            temp1 = (h * 1.0D) / height;
            temp2 = (w * 1.0D) / width;
            if (temp1 < temp2)
            {
                ss = w;
                os = width;
            }

            else
            {
                ss = h;
                os = height;
            }


            double per = (os * 1.0D) / ss;
            if (per < 1.0D)
            {
                h = (int)(h * per);
                w = (int)(w * per);
            }

            // create the thumbnail image
            System.Drawing.Image imag2 = img.GetThumbnailImage(w, h,
                 new System.Drawing.Image.GetThumbnailImageAbort(ImageAbort),
                 IntPtr.Zero);
            Bitmap tempBitmap = new Bitmap(w, h);
            System.Drawing.Image tempImg = System.Drawing.Image.FromHbitmap(tempBitmap.GetHbitmap());
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(tempImg);
            g.Clear(Color.White);

            int x, y;

            x = (tempImg.Width - imag2.Width) / 2;
            y = (tempImg.Height - imag2.Height) / 2;

            g.DrawImage(imag2, x, y, imag2.Width, imag2.Height);

            try
            {
                if (img != null)
                    img.Dispose();
                if (imag2 != null)
                    imag2.Dispose();
                if (tempBitmap != null)
                    tempBitmap.Dispose();

                string fileExtension = System.IO.Path.GetExtension(machpath).ToLower(); 
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                switch (fileExtension)
                {
                    case ".gif": tempImg.Save(SmallPath100, ImageFormat.Gif); break;
                    case ".jpg": tempImg.Save(SmallPath100, ImageFormat.Jpeg); break;
                    case ".bmp": tempImg.Save(SmallPath100, ImageFormat.Bmp); break;
                    case ".png": tempImg.Save(SmallPath100, ImageFormat.Png); break;
                }
                                
            }

            catch
            {
                throw new Exception("图片上传失败");
            }

            finally
            {
                //释放内存
                if (tempImg != null)
                    tempImg.Dispose();
                if (g != null)
                    g.Dispose();
            }

        }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值