ASP.NET 图片压缩,等比压缩图片

ASP.NET 图片压缩,等比压缩图片: 

public class shrink
    {
        /// <summary>
        /// 矩形框内部图片原比例压缩
        /// </summary>
        /// <param name="AbsoluteFileName">原路径</param>
        /// <param name="SaveServer">新存放路径</param>
        /// <param name="H">对应矩形高度</param>
        /// <param name="W">对应矩形宽度</param>
        /// <returns></returns>
        public string PicShrink(string AbsoluteFileName, string SaveServer,int H,int W)
        {
           
            using (Image img = Image.FromFile(AbsoluteFileName))
            {
                int OriginalHeight = img.Height; //原图高度
                int OriginalWeight = img.Width; //原图宽度
                int NewHeight = OriginalHeight;
                int NewWeight = OriginalWeight;
                double p = 0;//缩放比例
               
                //高度压缩比例小或相等[宽和高都溢出]
                if ((double)H / (double)OriginalHeight <= (double)W / (double)OriginalWeight)
                {
                    NewHeight = H;
                    p = (double)H / (double)OriginalHeight;
                    NewWeight = (int)Math.Round(p * OriginalWeight);
                }
                //宽度压缩比例小[宽和高都溢出]
                if ((double)H / (double)OriginalHeight > (double)W / (double)OriginalWeight)
                {
                    NewWeight = W;
                    p = (double)W / (double)OriginalWeight;
                    NewHeight = (int)Math.Round(p * OriginalHeight);
                }
                using (Bitmap bm = new Bitmap(NewWeight, NewHeight))
                {
                    Graphics grap = Graphics.FromImage(bm);
                    grap.Clear(Color.Transparent);  //指定图片背景色
                    Rectangle rt = new Rectangle(0, 0, NewWeight, NewHeight);
                    grap.DrawImage(img, rt);
                    string MathPath = System.Web.HttpContext.Current.Server.MapPath(SaveServer);
                    if (File.Exists(MathPath))
                    {
                        File.Delete(MathPath);
                    }
                    bm.Save(MathPath, ImageFormat.Jpeg);
                    bm.Dispose();
                    grap.Dispose();
                }
            }
            return SaveServer;
        }
    }

 

qq讨论群  :  171560784

posted @ 2013-04-28 11:56  kezhiping  阅读(533)  评论(0编辑  收藏  举报