C# 从图形对象GDI+;获取/设置像素;

C# 从图形对象GDI+;获取/设置像素;,c#,.net,graphics,pinvoke,gdi+,C#,.net,Graphics,Pinvoke,Gdi+,我正试图找到一种替代方案来获取/设置图形对象中特定位置的像素。 现在我正在使用GDI函数: [DllImport("gdi32.dll")] public static extern int GetPixel(System.IntPtr hdc, int nXPos, int nYPos); [DllImport("gdi32.dll")] public static extern uint SetPixel(IntPtr hdc, int X, int Y

我正试图找到一种替代方案来获取/设置图形对象中特定位置的像素。 现在我正在使用GDI函数:

    [DllImport("gdi32.dll")]
    public static extern int GetPixel(System.IntPtr hdc,  int nXPos,  int nYPos);

    [DllImport("gdi32.dll")]
    public static extern uint SetPixel(IntPtr hdc, int X, int Y, int crColor);
我找不到GDI+的任何。GetPixel/SetPixel似乎仅在位图对象上。 当图形由屏幕支持时,gdi32.dll的替代方案可以很好地工作,但当图形与位图一起使用时,它不再工作(GetPixel返回黑色,因为它在另一个位图(而不是实际位图)上工作):

一些示例代码:

private void ChangeImage(Graphics g)
{

        IntPtr gDC = IntPtr.Zero;

            try
            {
                gDC = g.GetHdc();


                // get the pixel color
                Color pixel = ColorTranslator.FromWin32(GetPixel(gDC, x, y));


                //change pixel object and persist
                SetPixel(gDC, x, y, ColorTranslator.ToWin32(pixel));

            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
            finally
            {
                if (gDC != IntPtr.Zero)
                    g.ReleaseHdc(gDC);
            }

}
是否有任何方法可以按像素分析图形对象? 图形对象表示用户可以在其中自由添加任何对象(包括手绘)的曲面。除此之外,我需要在一些屏幕部分应用过滤器(如模糊或像素化),以便访问图形中已经绘制的内容。 我还试图找到将当前图形持久化为位图的方法,并使用位图对象中的GetPixel,但我也找不到保存图形内容的方法


Thx

不,不可能直接从图形对象读取像素。要执行此操作,您需要访问底层HDC或位图对象。

图形始终是临时的。使用位图保存图像,然后可以调用
GetPixel
@L33TS。当然,它是临时的,因为它始终与设备上下文相关联:屏幕、图像、某些控件。但这并不意味着我们无法处理已经绘制的内容。这是个坏消息,因为当我需要保存对象时,底层对象有时是屏幕,有时是位图。虽然这段代码可能会回答这个问题,提供有关此代码为什么和/或如何回答此问题的其他上下文可提高其长期价值。请参阅注释。
    Dim bmap As New Bitmap(550, 100)
    Dim g As Graphics = Graphics.FromImage(bmap)

    ' Dont use the Graphics interface, use the BitMap interface
    DIM col as color = bmap.GetPixel(x,y)