2012-02-04 55 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結構,它代表圖像中剪輯內容的邊界框。

相關問題