本文實例講述了C#實現在服務器端裁剪圖片的方法。分享給大家供大家參考。具體實現方法如下:
//圖片路徑String oldPath = Server.MapPath("~/62223231.jpg");//新圖片路徑String newPath = System.IO.Path.GetExtension(oldPath);//設置截取的坐標和大小int x = 0, y = 20, width = 200, height = 2400;//計算新的文件名,在舊文件名后加_newnewPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_new" + newPath;Response.Write(oldPath);Response.Write("<br>");Response.Write(newPath);//定義截取矩形System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, width, height); //要截取的區域大小//加載圖片System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath)));//判斷超出的位置否if ((img.Width < x + width) || img.Height < y + height){ Response.Write("截取的區域超過了圖片本身的高度、寬度."); img.Dispose(); return;}//定義Bitmap對象System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);//進行裁剪System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);//保存成新文件bmpCrop.Save(newPath);//釋放對象img.Dispose();bmpCrop.Dispose();
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答