2012-02-04 56 views
2

嘿家伙我想知道是否有办法得到某个位图的某个区域?我试图制作一个瓷砖切割器,我需要它来遍历加载的瓷砖集,然后将图像剪切成xscale * yscale图像,然后单独保存它们。我目前正在使用这个为我的循环切割过程。得到一个位图的某个正方形区域

  int x_scale, y_scale, image_width, image_height; 

     image_width = form1.getWidth(); 
     image_height = form1.getHeight(); 
     x_scale = Convert.ToInt32(xs.Text); 
     y_scale = Convert.ToInt32(ys.Text); 

     for (int x = 0; x < image_width; x += x_scale) 
     { 
      for (int y = 0; y < image_height; y += y_scale) 
      { 
       Bitmap new_cut = form1.getLoadedBitmap();//get the already loaded bitmap 


      } 
     } 

那么有没有办法可以“选择”位图new_cut的一部分,然后保存该部分?

回答

4

您可以使用LockBits方法获取位图矩形区域的描述。类似于

// tile size 
var x_scale = 150; 
var y_scale = 150; 
// load source bitmap 
using(var sourceBitmap = new Bitmap(@"F:\temp\Input.png")) 
{ 
    var image_width = sourceBitmap.Width; 
    var image_height = sourceBitmap.Height; 
    for(int x = 0; x < image_width - x_scale; x += x_scale) 
    { 
     for(int y = 0; y < image_height - y_scale; y += y_scale) 
     { 
      // select source area 
      var sourceData = sourceBitmap.LockBits(
       new Rectangle(x, y, x_scale, y_scale), 
       System.Drawing.Imaging.ImageLockMode.ReadOnly, 
       sourceBitmap.PixelFormat); 
      // get bitmap for selected area 
      using(var tile = new Bitmap(
       sourceData.Width, 
       sourceData.Height, 
       sourceData.Stride, 
       sourceData.PixelFormat, 
       sourceData.Scan0)) 
      { 
       // save it 
       tile.Save(string.Format(@"F:\temp\tile-{0}x{1}.png", x, y)); 
      } 
      // unlock area 
      sourceBitmap.UnlockBits(sourceData); 
     } 
    } 
} 
+0

谢谢,作品很棒:)我学到了很多东西! – 2012-02-04 08:56:55

0

您可以使用Graphics对象的SetClip方法将图像区域剪裁成新图像。

一些重载需要一个Rectangle结构,它代表图像中剪辑内容的边界框。

相关问题