1. 程式人生 > >c#圖片生成縮圖,保持最高清的圖片

c#圖片生成縮圖,保持最高清的圖片

1.生成縮圖的主要程式碼

        /// <summary>
        /// 圖片顯示成縮圖
        /// </summary>
        /// <param name="sourcePath" >圖片原路徑</param>
        /// <param name="newPath">生成的縮圖新路徑</param>
        /// <param name="width">生成的縮圖寬度</param>
        /// <param name="height">生成的縮圖高度</param>
        public static void MakeThumbnail(string sourcePath, string newPath, int width, int height)
        {
            sourcePath = System.Web
.HttpContext.Current.Server.MapPath(sourcePath); newPath = System.Web.HttpContext.Current.Server.MapPath(newPath); System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath); int towidth = width; int toheight = height; int x = 0; int y
= 0; int ow = ig.Width; int oh = ig.Height; if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight) { oh = ig.Height; ow = ig.Height * towidth / toheight; y = 0; x = (ig.Width
- ow) / 2; } else { ow = ig.Width; oh = ig.Width * height / towidth; x = 0; y = (ig.Height - oh) / 2; } System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(System.Drawing.Color.Transparent); g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { throw ex; } finally { ig.Dispose(); bitmap.Dispose(); g.Dispose(); } }

2.具體操作流程
1.` protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(Server.MapPath(“現有圖片路徑”.ToString())))//判斷現有圖片路徑是否存在
{
S_ImageHelper.MakeThumbnail(“現有圖片路徑”.ToString(), “新建縮圖路徑”, 275, 254);
}

        Response.Write("成功");
}`

3。顯示成功,則縮圖生成好了,去看看你的新建路徑裡面是否又該圖片吧