2014-06-22 21 views
1

我有一個圖片框在我的程序之一,顯示我的圖片就好了。顯示的內容包括一個選定的「BackColor」和一些使用畫筆填充的矩形和一些使用筆的線條。我沒有導入的圖像。我需要檢索圖片框上指定像素的顏色值。我已經試過如下:如何從圖片框中獲取特定像素的顏色?

Bitmap b = new Bitmap(pictureBox1.Image);   
       Color colour = b.GetPixel(X,Y) 

pictureBox1.Image總是返回null.Image僅適用於導入的圖像嗎?如果沒有,我怎麼能得到這個工作?有沒有其他的選擇?

回答

1

是的你可以,但應該你?

這裏是你的代碼需要改變:

Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height); 
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle); 
Color colour = b.GetPixel(X, Y); 
b.Dispose(); 

但真的是有各地給予PictureBox真正Image,如果你想要做真正的工作,它與地方工作,如果你想這意味着沒有辦法使用它的可能性,例如其SizeMode

簡單地畫在它的背景上是不一樣的。爲此你可以(也應該)簡單地使用Panel。下面是一個最小的代碼來獲得分配一個真正的位圖:

public Form1() 
{ 
    InitializeComponent(); 
    pictureBox1.Image = new Bitmap(pictureBox1.ClientSize.Width, 
            pictureBox1.ClientSize.Height); 
    using (Graphics graphics = Graphics.FromImage(pictureBox1.Image)) 
    { 
    graphics.FillRectangle(Brushes.CadetBlue, 0, 0, 99, 99); 
    graphics.FillRectangle(Brushes.Beige, 66, 55, 66, 66); 
    graphics.FillRectangle(Brushes.Orange, 33, 44, 55, 66); 
    } 
} 

但是,如果你真的不想要分配的圖像可以使PictureBox繪製自身到一個真正的Bitmap。請注意,您需要Paint事件中繪製矩形等,才能使用! (其實你也必須使用Paint事件也是出於其他原因!)

現在你可以測試任何一種方式,例如,使用標籤和鼠標:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (pictureBox1.Image != null) 
    { // the 'real thing': 
     Bitmap bmp = new Bitmap(pictureBox1.Image); 
     Color colour = bmp.GetPixel(e.X, e.Y); 
     label1.Text = colour.ToString(); 
     bmp.Dispose(); 
    } 
    else 
    { // just the background: 
     Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height); 
     pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle); 
     Color colour = bmp.GetPixel(e.X, e.Y); 
     label1.Text = colour.ToString(); 
     bmp.Dispose(); 
    } 

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    e.Graphics.FillRectangle(Brushes.DarkCyan, 0, 0, 99, 99); 
    e.Graphics.FillRectangle(Brushes.DarkKhaki, 66, 55, 66, 66); 
    e.Graphics.FillRectangle(Brushes.Wheat, 33, 44, 55, 66); 
} 
+0

您給出的代碼的第一部分足以達到我的目的,但您的其他回覆也是很好的建議。感謝您花時間回答我的問題。 – user3765211

相關問題