2010-06-11 48 views
3

如何從圖形對象創建位圖對象?我想從我的Graphics對象讀取像素。例如,像System.Drawing.BitMap.GetPixel()。如何從Graphics對象創建位圖對象?

我想找出一個PDF文檔中的空白區域(全白色,或任何顏色),寫一些圖形/圖像。我已經嘗試過這樣,但它不起作用。爲什麼下面的代碼沒有按預期工作?

// 
// System.Drawing.Bitmap 
// System.Drawing.Graphics 
// 
Bitmap b = new Bitmap(width, height, graphics); 

// 
// In this case, for any (i, j) values, Bitmap.GetPixel returns 0 
// 
int rgb = b.GetPixel(i, j).ToArgb(); 

回答

0

最好要避免GetPixel/SetPixel和使用不安全的訪問方法的位圖一些速度(在.NET的唯一方面再次發佈此問題,刪除其他庫的依賴)。

System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

然後使用圖形實例。如果我記得,修改圖形對象會修改位圖。

+0

感謝您的回覆,MaLio。請在上面找到我的評論(回覆Belousov Pavel)。 – 2010-06-14 05:20:42

0

首先,您應該創建位圖,然後從該位圖創建圖形,使用圖形,然後保存(或使用它)位圖。

您的代碼將是這樣的:

using (Bitmap image = new Bitmap(X, Y)) 
{ 
    using (Graphics gr = Graphics.FromImage(image)) 
    { 
     // work with graphics, Draw objects 
    } 
    image.Save("YourPathToFile"); // Or GetPixel, if you want 
} 

您的代碼不工作,你除外,因爲位圖的構造變得只有圖形解決。 MSDN告訴Initializes a new instance of the Bitmap class with the specified size and with the resolution of the specified Graphics object.

+0

感謝您的回覆,Belousov。 - 我已經有一個圖形對象,從pdf構建(並且,我沒有相應的位圖對象,因爲渲染不是我的pdf庫的興趣)。我只想從中讀取像素,而我不想寫入/繪製它。我需要位圖對象來讀取像素,所以我試圖從圖形對象中構建位圖對象。 - 雖然寫入System.Drawing.Graphics對象非常容易,但從中讀取像素是故意不可能的。 – 2010-06-14 05:15:28

0

(很晚了,但是......)

你試過

var bmp = System.Drawing.Bitmap.FromHbitmap(gr.GetHdc()); 

然後你可以從bmp讀取的像素。

+1

對我而言,會引發System.Runtime.InteropServices.ExternalException。 – Michael 2016-05-19 13:20:01

+0

引發「GDI +中發生的一般錯誤」 – 2017-06-27 14:15:03