I'm working on a .NET C# project and would like to get the pixel value when I click a picturebox, how can I achieve that?
The basic idea is that when I click anywhere in the picturebox, I get the pixelvalue of that image point..
Thanks!
Use this:
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
Bitmap b = new Bitmap(pictureBox1.Image);
Color color = b.GetPixel(e.X, e.Y);
}
As @Hans pointed out Bitmap.GetPixel should work unless you have different SizeMode than PictureBoxSizeMode.Normal or PictureBoxSizeMode.AutoSize. To make it work all the time let's access private property of PictureBox named ImageRectangle.
PropertyInfo imageRectangleProperty = typeof(PictureBox).GetProperty("ImageRectangle", BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance);
private void pictureBox1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
MouseEventArgs me = (MouseEventArgs)e;
Bitmap original = (Bitmap)pictureBox1.Image;
Color? color = null;
switch (pictureBox1.SizeMode)
{
case PictureBoxSizeMode.Normal:
case PictureBoxSizeMode.AutoSize:
{
color = original.GetPixel(me.X, me.Y);
break;
}
case PictureBoxSizeMode.CenterImage:
case PictureBoxSizeMode.StretchImage:
case PictureBoxSizeMode.Zoom:
{
Rectangle rectangle = (Rectangle)imageRectangleProperty.GetValue(pictureBox1, null);
if (rectangle.Contains(me.Location))
{
using (Bitmap copy = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height))
{
using (Graphics g = Graphics.FromImage(copy))
{
g.DrawImage(pictureBox1.Image, rectangle);
color = copy.GetPixel(me.X, me.Y);
}
}
}
break;
}
}
if (!color.HasValue)
{
//User clicked somewhere there is no image
}
else
{
//use color.Value
}
}
}
Hope this helps
Unless that picturebox is in the size of a pixel, I don't think you can. Control onclick events doesn't save specific click location. If you are talking about color, not possible in c#
来源:https://stackoverflow.com/questions/18210030/get-pixelvalue-when-click-on-a-picturebox