如何在C#中获取矩形内的所有像素值

时间:2013-10-05 10:45:45

标签: c#

我正在开发一个程序来获取矩形内的所有像素。有一个图像控件,用户可以点击其中的一个部分。当用户单击特定位置时,将绘制一个矩形。我想获得该矩形内的所有像素。我现在要绘制矩形了。但我无法获得所有像素值。请找到用于绘制下方矩形的代码段。

private void panel1_Paint(object sender, PaintEventArgs e)
    {
        foreach (var rectKey in rectangles.Keys)
        {
            using (var pen = new Pen(rectKey))     //Create the pen used to draw the rectangle (using statement makes sure the pen is disposed)
            {
                //Draws all rectangles for the current color
                //Note that we're using the Graphics object that is passed into the event handler.
                e.Graphics.DrawRectangles(pen, rectangles[rectKey].ToArray()); 
            }
        }
    }

    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            Color c = System.Drawing.Color.GreenYellow ;     //Gets a color for which to draw the rectangle

            //Adds the rectangle using the color as the key for the dictionary
            if (!rectangles.ContainsKey(c))
            {
                rectangles.Add(c, new List<Rectangle>());
            }
            rectangles[c].Add(new Rectangle(e.Location.X - 12, e.Location.Y - 12, 25, 25));    //Adds the rectangle to the collection
        }
        //Make the panel repaint itself.
       panel1.Refresh();// Directs to panel1_Paint() event
       rectangles.Clear();
    }

1 个答案:

答案 0 :(得分:1)

在这种情况下,你必须使用Bitmap而不是图形对象。

Bitmap有一种方法可以在某个位置获取像素

    Bitmap bmp = Bitmap.FromFile("");

    // Get the color of a pixel within myBitmap.
    Color pixelColor = bmp.GetPixel(50, 50);

要读取矩形内的所有像素,您可以使用bmp.LockBits方法。