繁体   English   中英

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

[英]How to get all the pixel values inside a rectangle in 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();
    }

在这种情况下,您将不得不使用Bitmap而不是图形对象。

位图具有一种获取某个位置像素的方法

    Bitmap bmp = Bitmap.FromFile("");

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM