单击图片框时获取PixelValue
本文关键字:获取 PixelValue 单击 | 更新日期: 2023-09-27 18:27:34
我正在处理一个.NET C#项目,希望在单击图片框时获得像素值,如何实现?
基本想法是,当我点击图片框中的任何位置时,我都会得到该图像点的像素值。。
谢谢!
@Hans指出,除非SizeMode
与PictureBoxSizeMode.Normal or PictureBoxSizeMode.AutoSize
不同,否则Bitmap.GetPixel
应该有效。为了让它一直工作,让我们访问名为ImageRectangle
的PictureBox
的私有属性。
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
}
}
}
希望这能帮助
使用此:
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
Bitmap b = new Bitmap(pictureBox1.Image);
Color color = b.GetPixel(e.X, e.Y);
}
除非图片框有像素大小,否则我认为你做不到。Control onclick事件不会保存特定的单击位置。如果你谈论的是颜色,在c#中是不可能的