2011-09-20 69 views
1

我有一個問題,我有一個方法,需要一個圖像對象,處理它到1個顏色通道(其他2個是純黑色),然後從該過程返回一個新的圖像。方法不正確地返回圖像對象c#.Net

現在我遇到的問題是,當我在方法中創建新圖像,並在調試過程中查看對象時,圖像對象顯得非常好。但是當我返回一個空的圖像對象即Image對象裏面的屬性都秀「System.ArgumentException」

這裏是方法的代碼:

public Image GetRedImage(Image sourceImage) 
    { 
     using (Bitmap bmp = new Bitmap(sourceImage)) 
     using (Bitmap redBmp = new Bitmap(sourceImage.Width, sourceImage.Height)) 
     { 
      for (int x = 0; x < bmp.Width; x++) 
      { 
       for (int y = 0; y < bmp.Height; y++) 
       { 
        Color pxl = bmp.GetPixel(x, y); 
        Color redPxl = Color.FromArgb((int)pxl.R, 1, 1); 

        redBmp.SetPixel(x, y, redPxl); 
       } 
      } 
      Image tout = (Image)redBmp; 

      return tout; 
     } 

    } 

任何人有任何想法上什麼是地獄正在進行?

非常感謝。

回答

1

使用using塊你,只要你離開使用範圍配置的圖像。

嘗試從頂部更換這兩行:

using (Bitmap bmp = new Bitmap(sourceImage)) 
using (Bitmap redBmp = new Bitmap(sourceImage.Width, sourceImage.Height)) 

有:

Bitmap bmp = new Bitmap(sourceImage); 
Bitmap redBmp = new Bitmap(sourceImage.Width, sourceImage.Height); 

現在它應該工作,這取決於你的程序邏輯,你將不得不處理這些圖像之後手動。

你很可能在處理bmp還與使用,但肯定不是redBmp對象,你基本上恢復了,所以要麼你克隆它並返回一個克隆,或者你不處理它,或者你返回位於無法使用對象就像現在發生的事情一樣。

+0

*咧嘴* 三江源所有您的幫助(尤其是達維德) 返回正確現在 很多很多的感謝 – Gelion

+1

再投答案,並接受你認爲最好的一個;-) –

3

redBmp被您的使用塊丟棄,並且tout將redBmp轉換爲Image類型。刪除redBmp的使用塊。

1

你在using聲明包裹redBmp以便它Dispose方法調用的方法退出時。如果你打算在方法之外使用它(你已經將它作爲Image投下並且正在返回它),你不應該處理它。

public Image GetRedImage(Image sourceImage) 
{ 
    Bitmap redBmp = null; 
    using (Bitmap bmp = new Bitmap(sourceImage)) 
    { 
     redBmp = new Bitmap(sourceImage.Width, sourceImage.Height); 
     for (int x = 0; x < bmp.Width; x++) 
     { 
      for (int y = 0; y < bmp.Height; y++) 
      { 
       Color pxl = bmp.GetPixel(x, y); 
       Color redPxl = Color.FromArgb((int)pxl.R, 1, 1); 

       redBmp.SetPixel(x, y, redPxl); 
      } 
     } 
    } 

    return redBmp as Image; 
}