最近項目要求實現不規則裁剪功能。本來想用html5的canvas在前端實現的,但是發現有點困難,以下為C#端對圖對片的處理。 好了,那就開始貼代碼了 以下為一個按鈕的事件,為裁剪准備圖片、裁剪路徑、保存路徑 private void button1_Click(object sender, EventArgs e) { GraphicsPath path = new GraphicsPath(); Point[] p = { new Point(424,244), new Point(240,440), new Point(340,552), new Point(550,526), new Point(478,366), new Point(348,660), new Point(424,244) }; path.AddLines(p); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = @"Bitmap文件(*.bmp)|*.bmp|Jpeg文件(*.jpg)|*.jpg|所有合適文件(*.bmp,*.jpg)|*.bmp;*.jpg"; openFileDialog.FilterIndex = 3; openFileDialog.RestoreDirectory = true; if (DialogResult.OK == openFileDialog.ShowDialog()) { Bitmap bit = (Bitmap)Bitmap.FromFile(openFileDialog.FileName, false); Bitmap newBit = null; BitmapCrop(bit, path, out newBit); newBit.Save(@"C:\Users\Public\Pictures\Sample Pictures\沙漠22.jpg"); } } 以下為裁剪的關鍵代碼 /// <summary> /// 圖片截圖 /// </summary> /// <param name="bitmap">原圖</param> /// <param name="path">裁剪路徑</param> /// <param name="outputBitmap">輸出圖</param> /// <returns></returns> public static Bitmap BitmapCrop(Bitmap bitmap, GraphicsPath path, out Bitmap outputBitmap) { RectangleF rect = path.GetBounds(); int left = (int)rect.Left; int top = (int)rect.Top; int width = (int)rect.Width; int height = (int)rect.Height; Bitmap image = (Bitmap)bitmap.Clone(); outputBitmap = new Bitmap(width, height); for (int i = left; i < left + width; i++) { for (int j = top; j < top + height; j++) { //判斷坐標是否在路徑中 if (path.IsVisible(i, j)) { //復制原圖區域的像素到輸出圖片 outputBitmap.SetPixel(i - left, j - top, image.GetPixel(i, j)); //設置原圖這部分區域為透明 image.SetPixel(i, j, Color.FromArgb(0, image.GetPixel(i, j))); } else { outputBitmap.SetPixel(i - left, j - top, Color.FromArgb(0, 255, 255, 255)); } } } bitmap.Dispose(); return image; } 有了這個前台只需要獲取用戶的鼠標路徑傳到後台就可以。