c# web 多图上传,保存原图,800*800,400*400缩略图
帮助类内容:
1.基本上传图片
2.上传图片(原图上传,自定义路径和名称)
3.上传图片(图片byte[],自定义路径和名称)
4.上传等比缩放图片
5.给图片加上水印
6.产生图片验证码
7.根据地址获取图片宽和高
8.根据地址获取图片高度
9.图片无损压缩上传
业务源码
引用命名空间
using QuanXi.Web.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;业务逻辑代码
private void UploadImgs(HttpContext context)
        {
            HttpFileCollection files = context.Request.Files;
            StringBuilder sb = new StringBuilder();
            var path = "/uploads/base/photo/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM")+ DateTime.Now.ToString("dd") + "/";
            string imgsurl = "",imgurls="",imgurlb="";
            if (files.Count <= 0)
            {
                sb.Append("{\"status\": \"-1\",\"msg\":\"未收到上传图片\"}");
            }
            else
            {
                for (int i = 0; i < files.Count; i++)
                {
                    var strPath = path + files[i].FileName;
                    //files[i].SaveAs(strPath);
                    HttpPostedFile imgfile = files[i];
                    //文件真实类型
                    string strFileType = imgfile.ContentType;
                    
                    string strFileName = imgfile.FileName;
                    //文件扩展名
                    string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
                    if (strFileType.StartsWith("image") && (strFileExtendName == "bmp" || strFileExtendName == "jpg" || strFileExtendName == "jpeg" || strFileExtendName == "png" || strFileExtendName == "gif"))
                    {
                        //文件大小
                        long intFileSize = imgfile.ContentLength;
                        //取当前时间的字符串                    
                        string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                        //文件的新名称
                        string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName;
                        //保存原图
                        AttachmentInfo imgresult = ImageHelper.UploadImage(imgfile, path, strNewFileName);
                        
                        imgsurl += imgresult.FileUrl + "|";
                        Stream stmUpload = imgfile.InputStream;
                        
                        //保存压缩后的小图
                        Stream sstmUpload = stmUpload;
                        ImageInfo othumb1 = new ImageInfo();
                        othumb1.Width = 400;
                        othumb1.Height = 400;
                        othumb1.Tag = "s";
                        string sSaveFile = HttpContext.Current.Server.MapPath(path) + othumb1.Tag + "_" + strNewFileName;
                        if (ImageHelper.ResizeImage(sstmUpload, sSaveFile, othumb1.Width, othumb1.Height))
                        {
                            imgurls += path + othumb1.Tag + "_" + strNewFileName + "|";
                        }
                        //sstmUpload.Close();
                        //sstmUpload.Dispose();
                        //保存压缩后的大图
                        Stream bstmUpload = stmUpload;
                        ImageInfo othumb2 = new ImageInfo();
                        othumb2.Width = 800;
                        othumb2.Height = 800;
                        othumb2.Tag = "b";
                        string bSaveFile = HttpContext.Current.Server.MapPath(path) + othumb2.Tag + "_" + strNewFileName;
                        if(ImageHelper.ResizeImage(bstmUpload, bSaveFile, othumb2.Width, othumb2.Height))
                        {
                            imgurlb += path + othumb2.Tag + "_" + strNewFileName + "|";
                        }
                        stmUpload.Close();
                        stmUpload.Dispose();
                    }
                }
                if (imgsurl.LastIndexOf("|")==imgsurl.Length-1)
                {
                    imgsurl = imgsurl.Substring(0, imgsurl.Length - 1);
                }
                if (imgurls.LastIndexOf("|") == imgurls.Length-1)
                {
                    imgurls = imgurls.Substring(0,imgurls.Length-1);
                }
                if (imgurlb.LastIndexOf("|")== imgurlb.Length-1)
                {
                    imgurlb = imgurlb.Substring(0,imgurlb.Length-1);
                }
                sb.Append("{\"status\": \"0\",\"msg\":\"上传成功\",\"imgsurl\":\""+ imgsurl + "\",\"imgurls\":\"" + imgurls + "\",\"imgurlb\":\"" + imgurlb + "\"}");
            }
            string strCallBack = RequestProcess.RequestString("callback");
            if (strCallBack != "")
            {
                HttpContext.Current.Response.Write(strCallBack + "(" + sb.ToString() + ");");
                HttpContext.Current.Response.End();
            }
            else
            {
                HttpContext.Current.Response.Write(sb.ToString());
                HttpContext.Current.Response.End();
            }
        }返回结果
{
    "status":"0",
    "msg":"上传成功",
    "imgsurl":"/uploads/base/photo/2022/0323//2022323953078996789.jpg",
    "imgurls":"/uploads/base/photo/2022/0323/s_2022323953078996789.jpg",
    "imgurlb":"/uploads/base/photo/2022/0323/b_2022323953078996789.jpg"
}imgsurl:原图
imgurls:压缩后的小图 400*400
imgurlb:压缩后的大图 800*800
  
图片上传帮助类 ImageHelper.cs
引用命名空间
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;帮助类 ImageHelper.cs
public class ImageInfo
    {
        private int m_intWidth = 0;
        private int m_intHeight = 0;
        private string m_strTag = "";
        public int Width
        {
            set { m_intWidth = value; }
            get { return m_intWidth; }
        }
        public int Height
        {
            set { m_intHeight = value; }
            get { return m_intHeight; }
        }
        public string Tag
        {
            set { m_strTag = value; }
            get { return m_strTag; }
        }
    }
    public class ImageHelper
    {
        #region 上传图片
        /// <summary>
        /// 
        /// </summary>
        /// <param name="postedFile">上传过的文件</param>
        /// <param name="upLoadForder">分类过的路径</param>
        /// <param name="isSaveOriginal">是否保持原来的路径</param>
        /// <param name="isWaterImage"></param>
        /// <param name="thumbnails">图片信息</param>
        /// <returns></returns>
        static public AttachmentInfo UploadImage(HttpPostedFile postedFile, string upLoadForder, bool isSaveOriginal, bool isWaterImage, List<ImageInfo> thumbnails)
        {
            string strRootFolder = "";
            AttachmentInfo oaiInfo = new AttachmentInfo();
            //文件名
            string strFileName = postedFile.FileName;
            //文件扩展名
            string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
            //文件真实类型
            string strFileType = postedFile.ContentType;
            //文件大小
            int intFileSize = postedFile.ContentLength;
            //文件上传的文件夹目录(绝对路径)
            string strFolderMapPath;
            if (!upLoadForder.Equals(""))
            {
                strFolderMapPath = HttpContext.Current.Server.MapPath(upLoadForder);
            }
            else
            {
                strFolderMapPath = HttpContext.Current.Server.MapPath("/uploads/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/");
            }
            //建立上传目录
            if (!Directory.Exists(strFolderMapPath))
            {
                Directory.CreateDirectory(strFolderMapPath);
            }
            //取当前时间的字符串                    
            string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            //文件的新名称(当前日期+文件大小+文件扩展名)
            string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName;
            //最终保存文件的路径(文件绝对路径+新生成的文件的新名称)
            string strFileMapPath = strFolderMapPath + "/" + strNewFileName;
            //返回的文件虚拟目录(相对路径)
            string strFileUploadPath = upLoadForder + "/" + strNewFileName;
            #region  如果为图片类型
            if (strFileType.StartsWith("image") && (strFileExtendName == "bmp" || strFileExtendName == "jpg" || strFileExtendName == "jpeg" || strFileExtendName == "png" || strFileExtendName == "gif"))
            {
                //是否保存原图
                if (isSaveOriginal)
                {
                    //保存原图
                    postedFile.SaveAs(strFileMapPath);
                }
                if (thumbnails != null && thumbnails.Count > 0)
                {
                    string strSaveFile = "";
                    foreach (ImageInfo thumb in thumbnails)
                    {
                        if (thumb.Tag != "")
                        {
                            strSaveFile = strFolderMapPath + "/" + thumb.Tag + "_" + strNewFileName;
                        }
                        else
                        {
                            strSaveFile = strFolderMapPath + "/" + strNewFileName;
                        }
                        ResizeImage(postedFile.InputStream, strSaveFile, thumb.Width, thumb.Height);
                    }
                }
            }
            #endregion
            else
            {
                //保存文件
                postedFile.SaveAs(strFileMapPath);
            }
            //HttpContext.Current.Response.Write(strFileUploadPath);
            //附件属性
            oaiInfo.FileName = strNewFileName;
            oaiInfo.FilePath = upLoadForder;
            oaiInfo.FileUrl = upLoadForder + strNewFileName;
            oaiInfo.FileSize = intFileSize;
            return oaiInfo;
        }
        #endregion
        #region 上传图片(原图上传,自定义路径和名称)
        /// <summary>
        /// 上传图片(原图上传,自定义路径和名称)
        /// </summary>
        /// <param name="postedFile">上传控件</param>
        /// <param name="filePath">存放相对路径</param>
        /// <param name="fileName">新文件名</param>
        /// <returns></returns>
        static public AttachmentInfo UploadImage(HttpPostedFile postedFile, string filePath, string fileName)
        {
            AttachmentInfo oaiInfo = new AttachmentInfo();
            文件名
            string strFileName = postedFile.FileName;
            //文件扩展名
            string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
            //文件真实类型
            string strFileType = postedFile.ContentType;
            //文件大小
            int intFileSize = postedFile.ContentLength;
            //文件上传的文件夹目录(绝对路径)
            string strFolderMapPath = HttpContext.Current.Server.MapPath(filePath);
            //建立上传目录
            if (!Directory.Exists(strFolderMapPath))
            {
                Directory.CreateDirectory(strFolderMapPath);
            }
            //最终保存文件的路径(文件绝对路径+新生成的文件的新名称)
            string strFileMapPath = strFolderMapPath + "/" + fileName;
            //返回的文件虚拟目录(相对路径)
            string strFileUploadPath = filePath + "/" + fileName;
            oaiInfo.ErrorDescription = "";
            //保存原图
            try
            {
                postedFile.SaveAs(strFileMapPath);
            }
            catch (Exception ex)
            {
                oaiInfo.ErrorDescription = ex.Message;
            }
            //附件属性
            oaiInfo.FileName = fileName;
            oaiInfo.FilePath = filePath;
            oaiInfo.FileUrl = strFileUploadPath;
            oaiInfo.FileSize = intFileSize;
            return oaiInfo;
        }
        #endregion
        # region 上传图片(图片byte[],自定义路径和名称)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="imgbytes">图片byte</param>
        /// <param name="filePath">文件夹目录</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        static public AttachmentInfo UploadImage(byte[] imgbytes, string filePath, string fileName)
        {
            AttachmentInfo oaiInfo = new AttachmentInfo();
            //文件上传的文件夹目录(绝对路径)
            string strFolderMapPath = HttpContext.Current.Server.MapPath(filePath);
            //建立上传目录
            if (!Directory.Exists(strFolderMapPath))
            {
                Directory.CreateDirectory(strFolderMapPath);
            }
            //文件大小
            int intFileSize = imgbytes.Length;
            //最终保存文件的路径(文件绝对路径+新生成的文件的新名称)
            string strFileMapPath = strFolderMapPath + "/" + fileName;
            //返回的文件虚拟目录(相对路径)
            string strFileUploadPath = filePath + "/" + fileName;
            oaiInfo.ErrorDescription = "";
            using (MemoryStream ms = new MemoryStream(imgbytes))
            {
                try
                {
                    Bitmap bmp = new Bitmap(ms);
                    Bitmap bmpnew = new Bitmap(bmp);
                    bmp.Dispose();
                    bmp = null;
                    bmpnew.Save(strFileMapPath, ImageFormat.Jpeg);
                    bmpnew.Dispose();
                }
                catch(Exception e)
                {
                    oaiInfo.ErrorDescription = e.Message;
                }
            }
            oaiInfo.FileName = fileName;
            oaiInfo.FilePath = strFileMapPath;
            oaiInfo.FileUrl = strFileUploadPath;
            oaiInfo.FileSize = intFileSize;
            return oaiInfo;
        }
        #endregion
        #region 等比缩放图片
        public static bool ResizeImage(Stream imageStream, string strSavePath, int width, int height)
        {
            bool blnRtn = false;
            try
            {
                //创建图片对象
                System.Drawing.Image image, resizeimage;
                System.Drawing.Image.GetThumbnailImageAbort callb = null;
                //获得图片源
                image = System.Drawing.Image.FromStream(imageStream);
                //计算图片的宽度和高度
                double dobWidth = image.Width;
                double dobHeight = image.Height;
                //重新计算图片等比缩放后的宽度和高度(这里写的比较麻烦,你们看看又没有更好的办法)
                if (dobWidth > width || dobHeight > height)
                {
                    if (dobWidth > dobHeight)
                    {
                        dobHeight = (int)(dobHeight * (width / dobWidth));
                        dobWidth = width;
                        if (dobHeight > height)
                        {
                            dobWidth = (int)(dobWidth * (height / dobHeight));
                            dobHeight = height;
                        }
                    }
                    else
                    {
                        dobWidth = (int)(dobWidth * (height / dobHeight));
                        dobHeight = height;
                        if (dobWidth > width)
                        {
                            dobHeight = (int)(dobHeight * (width / dobWidth));
                            dobWidth = width;
                        }
                    }
                }
                else
                {
                }
                //缩放后图片
                resizeimage = image.GetThumbnailImage((int)dobWidth, (int)dobHeight, callb, new System.IntPtr());
                //保存图片
                resizeimage.Save(strSavePath);
                //释放resizeimage对象的资源
                image.Dispose();
                //释放resizeimage对象的资源
                resizeimage.Dispose();
                blnRtn = true;
                //imageStream.Close();
                //imageStream.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("ex:" + ex.Message);
                blnRtn = false;
            }
            return blnRtn;
        }
        #endregion
        #region 给图片加上水印
        public static bool WaterImage(Stream imageStream, string strSavePath)
        {
            bool blnRtn = false;
            try
            {
                //获得图片源和水印图片源
                System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream);
                System.Drawing.Image imageWater = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("/watermark.png"));
                //根据图片源创建BitMap
                Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
                Graphics g = Graphics.FromImage(bitmap);
                //计算画框的宽度高度以及位置
                float rectWidth = imageWater.Width;
                float rectHeight = imageWater.Height;
                float rectX = image.Width - imageWater.Width;
                float rectY = image.Height - imageWater.Height;
                //加上水印
                g.DrawImage(imageWater, rectX, rectY, rectWidth, rectHeight);
                //释放对象
                image.Dispose();
                imageWater.Dispose();
                //保存图片
                bitmap.Save(strSavePath, ImageFormat.Jpeg);
                //释放对象
                g.Dispose();
                bitmap.Dispose();
            }
            catch
            {
                blnRtn = false;
            }
            return blnRtn;
        }
        #endregion
        #region 产生图片验证码
        /// <summary>
        /// 产生图片验证码
        /// </summary>
        /// <param name="checkCode"></param>
        public static void CreateCheckImage(string checkCode)
        {
            if ((checkCode != null) && !(checkCode.Trim() == string.Empty))
            {
                Bitmap image = new Bitmap((int)Math.Ceiling((double)(checkCode.Length * 12.5)), 0x16);
                Graphics graphics = Graphics.FromImage(image);
                try
                {
                    int num;
                    Random random = new Random();
                    graphics.Clear(Color.White);
                    for (num = 0; num < 0x19; num++)
                    {
                        int num2 = random.Next(image.Width);
                        int num3 = random.Next(image.Width);
                        int num4 = random.Next(image.Height);
                        int num5 = random.Next(image.Height);
                        graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5);
                    }
                    Font font = new Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold);
                    LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                    graphics.DrawString(checkCode, font, brush, (float)2f, (float)2f);
                    for (num = 0; num < 100; num++)
                    {
                        int x = random.Next(image.Width);
                        int y = random.Next(image.Height);
                        image.SetPixel(x, y, Color.FromArgb(random.Next()));
                    }
                    graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                    MemoryStream stream = new MemoryStream();
                    image.Save(stream, ImageFormat.Gif);
                    HttpContext.Current.Response.ClearContent();
                    HttpContext.Current.Response.ContentType = "image/Gif";
                    HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                }
                finally
                {
                    graphics.Dispose();
                    image.Dispose();
                }
            }
        }
        public byte[] CreateImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == string.Empty) return null;
            //生成BitMap图像
            Bitmap image = new Bitmap((int)Math.Ceiling((double)(checkCode.Length * 12.5)), 0x16);
            Graphics graphics = Graphics.FromImage(image);
            try
            {
                int num;
                Random random = new Random();
                graphics.Clear(Color.White);
                for (num = 0; num < 0x19; num++)
                {
                    int num2 = random.Next(image.Width);
                    int num3 = random.Next(image.Width);
                    int num4 = random.Next(image.Height);
                    int num5 = random.Next(image.Height);
                    graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5);
                }
                Font font = new Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold);
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                graphics.DrawString(checkCode, font, brush, (float)2f, (float)2f);
                for (num = 0; num < 100; num++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                graphics.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                //将图像保存到指定流
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return ms.ToArray();
            }
            finally
            {
                graphics.Dispose();
                image.Dispose();
            }
        }
        #endregion
        /// <summary>
        /// 根据地址图片宽和高
        /// </summary>
        /// <param name="strImageUrl"></param>
        /// <returns></returns>
        public static ImageInfo GetImageSize(string strImageUrl)
        {
            ImageInfo imageInfo = new ImageInfo();
            strImageUrl = HttpContext.Current.Server.MapPath(strImageUrl);
            if (File.Exists(strImageUrl))
            {
                Image imageOb = Image.FromFile(strImageUrl);
                imageInfo.Width = imageOb.Width;
                imageInfo.Height = imageOb.Height;
            }
            return imageInfo;
        }
        /// <summary>
        /// 根据地址图片高度
        /// </summary>
        /// <param name="strImageUrl"></param>
        /// <returns></returns>
        public static int GetImageHeight(string strImageUrl)
        {
            return GetImageSize(strImageUrl).Height;
        }
        // 影音快传图片地址
        // 手机端域名为m.user.xxxx.cc,电脑端域名为my.xxxx.cc
        // 导致影音快传页面调用时缺省域名图片不显示,所以在上传时直接以绝对地址形式上传
        public static string setImgUrl(string strImgUrl)
        {
            if (strImgUrl.Contains("http") && strImgUrl.Contains("xxxx"))
            {
                return strImgUrl;
            }
            if (!strImgUrl.Contains("http") && strImgUrl.Contains("xxxx"))
            {
                return "http://" + strImgUrl;
            }
            if (!strImgUrl.Contains("http") && !strImgUrl.Contains("xxxx"))
            {
                return "http://user.m.xxxx.cc" + strImgUrl;
            }
            return strImgUrl;
        }
        public static bool SaveImage(Stream imageStream, string strSavePath)
        {
            bool blnRtn = false;
            try
            {
                //创建图片对象
                System.Drawing.Image image, resizeimage;
                System.Drawing.Image.GetThumbnailImageAbort callb = null;
                //获得图片源
                image = System.Drawing.Image.FromStream(imageStream);
                image.Save(strSavePath);
                //释放resizeimage对象的资源
                image.Dispose();
                blnRtn = true;
                //imageStream.Close();
                //imageStream.Dispose();
            }
            catch (Exception ex)
            {
                //throw new Exception("ex:" + ex.Message);
                blnRtn = false;
            }
            return blnRtn;
        }
        #region 图片无损压缩
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            try
            {
                //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
                FileInfo firstFileInfo = new FileInfo(sFile);
                if (sfsc == true && firstFileInfo.Length < size * 1024)
                {
                    firstFileInfo.CopyTo(dFile, true);
                    return true;
                }
                Image iSource = Image.FromFile(sFile);
                ImageFormat tFormat = iSource.RawFormat;
                int dHeight = iSource.Height / 2;
                int dWidth = iSource.Width / 2;
                int sW = 0, sH = 0;
                //按比例缩放
                Size tem_size = new Size(iSource.Width, iSource.Height);
                if (tem_size.Width > dHeight || tem_size.Width > dWidth)
                {
                    if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                    {
                        sW = dWidth;
                        sH = (dWidth * tem_size.Height) / tem_size.Width;
                    }
                    else
                    {
                        sH = dHeight;
                        sW = (tem_size.Width * dHeight) / tem_size.Height;
                    }
                }
                else
                {
                    sW = tem_size.Width;
                    sH = tem_size.Height;
                }
                Bitmap ob = new Bitmap(dWidth, dHeight);
                Graphics g = Graphics.FromImage(ob);
                g.Clear(Color.WhiteSmoke);
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
                g.Dispose();
                //以下代码为保存图片时,设置压缩质量
                EncoderParameters ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0] = flag;//设置压缩的比例1-100
                EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;
                try
                {
                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo jpegICIinfo = null;
                    for (int x = 0; x < arrayICI.Length; x++)
                    {
                        if (arrayICI[x].FormatDescription.Equals("JPEG"))
                        {
                            jpegICIinfo = arrayICI[x];
                            break;
                        }
                    }
                    if (jpegICIinfo != null)
                    {
                        ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                        FileInfo fi = new FileInfo(dFile);
                        if (fi.Length > 1024 * size)
                        {
                            flag = flag - 10;
                            CompressImage(sFile, dFile, flag, size, false);
                        }
                    }
                    else
                    {
                        ob.Save(dFile, tFormat);
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    iSource.Dispose();
                    ob.Dispose();
                }
            }
            catch
            {
                return false;
            }
            
        }
        #endregion
    }                










