1. 程式人生 > 其它 >C#實現圖片切割的方法

C#實現圖片切割的方法

本文例項講述了C#實現圖片切割的方法。分享給大家供大家參考,具體如下:

圖片切割就是把一幅大圖片按使用者要求切割成多幅小圖片。dotnet環境下系統提供了GDI+類庫,為影象操作處理提供了方便的介面。

下面是影象切割小程式:

 1 public class ImageManager
 2 {
 3   /// <summary>
 4   /// 影象切割
 5   /// </summary>
 6   /// <param name="url">影象檔名稱</param>
 7   /// <param name="width">
切割後圖像寬度</param> 8 /// <param name="height">切割後圖像高度</param> 9 /// <param name="savePath">切割後圖像檔案儲存路徑</param> 10 /// <param name="fileExt">切割後圖像副檔名</param> 11 public static void Cut(string url, int width, int height,string savePath,string
fileExt,string logofile) 12 { 13 Bitmap bitmap = new Bitmap(url); 14 Decimal MaxRow = Math.Ceiling((Decimal)bitmap.Height / height); 15 Decimal MaxColumn = Math.Ceiling((decimal)bitmap.Width / width); 16 for (decimal i = 0; i < MaxRow; i++) 17 { 18 for (decimal j = 0; j < MaxColumn; j++)
19 { 20 string filename = i.ToString() + "," + j.ToString() + "." + fileExt; 21 Bitmap bmp = new Bitmap(width, height); 22 for (int offsetX = 0; offsetX < width; offsetX++) 23 { 24 for (int offsetY = 0; offsetY < height; offsetY++) 25 { 26 if (((j * width + offsetX) < bitmap.Width) && ((i * height + offsetY) < bitmap.Height)) 27 { 28 bmp.SetPixel(offsetX, offsetY, bitmap.GetPixel((int)(j * width + offsetX), (int)(i * height + offsetY))); 29 } 30 } 31 } 32 Graphics g = Graphics.FromImage(bmp); 33 g.DrawString("指令碼之家", new Font("黑體", 20), new SolidBrush(Color.FromArgb(70, Color.WhiteSmoke)), 60, height/2);//加水印 34 ImageFormat format = ImageFormat.Png; 35 switch (fileExt.ToLower()) 36 { 37 case "png": 38 format = ImageFormat.Png; 39 break; 40 case "bmp": 41 format = ImageFormat.Bmp; 42 break; 43 case "gif": 44 format = ImageFormat.Gif; 45 break; 46 } 47 bmp.Save(savePath+"//" + filename,format); 48 } 49 } 50 } 51 }