单击图片框时获取PixelValue
我正在研究一个.NET C#项目,并希望在点击一个图片框时获得像素值,我该如何实现呢?
基本的想法是,当我点击图片框中的任何地方时,我得到该图像点的像素值。
谢谢!
用这个:
private void pictureBox2_MouseUp(object sender, MouseEventArgs e) { Bitmap b = new Bitmap(pictureBox1.Image); Color color = b.GetPixel(eX, eY); }
正如@Hans所指出的, Bitmap.GetPixel
应该可以工作,除非你有与PictureBoxSizeMode.Normal or PictureBoxSizeMode.AutoSize
不同的SizeMode
。 为了让它一直工作,让我们访问PictureBox
的私有属性,命名为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 } } }
希望这可以帮助
除非那个图片框的大小像素,我认为你不能。 控制onclick事件不会保存特定的点击位置。 如果你在谈论颜色,c#中不可能