C#图像裁剪,分割,保存

如主题中所述,我有一个图像:

private Image testing; testing = new Bitmap(@"sampleimg.jpg"); 

我想把它分成3 x 3矩阵,总共9个图像,并保存它。这么简单的任何提示或技巧? 我正在使用视觉工作室2008并致力于智能设备。 试过一些方法,但我无法得到它。 这是我试过的:

  int x = 0; int y = 0; int width = 3; int height = 3; int count = testing.Width / width; Bitmap bmp = new Bitmap(width, height); Graphics g = Graphics.FromImage(bmp); for (int i = 0; i < count; i++) { g.Clear(Color.Transparent); g.DrawImage(testing, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); bmp.Save(Path.ChangeExtension(@"C\AndrewPictures\", String.Format(".{0}.bmp",i))); x += width; } 

根据.NET版本,您可以执行以下操作之一来裁剪:

.NET 2.0

 private static Image cropImage(Image img, Rectangle cropArea) { Bitmap bmpImage = new Bitmap(img); Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); return (Image)(bmpCrop); } 

.NET 3.5+

 // Create an Image element. Image croppedImage = new Image(); croppedImage.Width = 200; croppedImage.Margin = new Thickness(5); // Create a CroppedBitmap based off of a xaml defined resource. CroppedBitmap cb = new CroppedBitmap( (BitmapSource)this.Resources["masterImage"], new Int32Rect(30, 20, 105, 50)); //select region rect croppedImage.Source = cb; //set image source to cropped 

如您所见,它比您正在做的更简单。 第一个示例克隆当前图像并获取其子集; 第二个示例使用CroppedBitmap ,它支持从构造函数中直接获取图像的一部分。

分割部分是简单的数学,只是将图像分成9组坐标并将它们传递给构造函数。