关于C#中PictureBox取像素问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 16:09:48
我用PictureBox的Graphics对象在PictureBox中进行绘图,然后想取出PictureBox中某一点的像素颜色,请问该如何取?在线等……
我使用的是Graphics对象来绘图的,所以PictureBox对象的Image属性是null,没有办法先将PictureBox的图像转换为Image再获取颜色。

Bitmap bmp = (Bitmap)pictureBox1.Image;
先将pictureBox1的图像转换成位图图像
Color color = bmp.GetPixel(0, 0);
再用GetPixel方法获取颜色

新代码修改如下

先声明位图对象
Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);

将pictureBox1的图像绘制到位图里
pictureBox1.DrawToBitmap(bmp, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));

获取坐标1,1的颜色
MessageBox.Show(bmp.GetPixel(1, 1).ToString());

可以用API函数获得

using System.Runtime.InteropServices;

[DllImport("gdi32.dll", EntryPoint = "GetPixel")]
public static extern int GetPixel(int hdc, int x, int y);
private void button1_Click(object sender, EventArgs e)
{
Graphics g = pictureBox1.CreateGraphics();
g.FillRectangle(Brushes.Red, new Rectangle(0, 0, 40, 40));
Point point = pictureBox1.PointToClient(MousePosition);//当前鼠标的位置
IntPtr intptr = g.G