我的一个程序中有一个图片框,可以很好地显示我的图像。显示的内容包括一个选定的“ BackColor”以及一些使用画笔填充的矩形和一些使用笔绘制的线。我没有导入的图像。我需要检索图片框上指定像素的颜色值。我尝试了以下方法:
Bitmap b = new Bitmap(pictureBox1.Image);
Color colour = b.GetPixel(X,Y)
Run Code Online (Sandbox Code Playgroud)
但pictureBox1.Image总是回报null。难道.Image只能用导入的图像工作?如果没有,我该如何工作?还有其他选择吗?
是的,您可以,但是应该吗?
这是您的代码需要进行的更改:
Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);
Color colour = b.GetPixel(X, Y);
b.Dispose();
Run Code Online (Sandbox Code Playgroud)
但真正让周围的没有办法PictureBox真正的Image工作某处,如果你想要做真正的工作吧,如果你想使用它的可能性,例如其含义SizeMode。
简单地绘制背景是不一样的。这是获得分配的真实位图的最少代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您真的不想分配图像,则可以将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);
}
Run Code Online (Sandbox Code Playgroud)