如何从Graphics对象创建Bitmap对象?

时间:2010-06-11 10:10:29

标签: .net graphics bitmap getpixel

如何从Graphics对象创建Bitmap对象?我想从我的Graphics对象中读取像素。例如,像System.Drawing.BitMap.GetPixel()。

我试图在pdf文档中找出空白区域(全白或任何颜色),以编写一些图形/图像。我试过这样,但它没有用。为什么下面的代码没有按预期工作?

//
// System.Drawing.Bitmap
// System.Drawing.Graphics
//
Bitmap b = new Bitmap(width, height, graphics);

//
// In this case, for any (i, j) values, Bitmap.GetPixel returns 0
//
int rgb = b.GetPixel(i, j).ToArgb();

(在.net-only上下文中再次发布此问题,删除其他库依赖项)

3 个答案:

答案 0 :(得分:0)

理想情况下,您希望避免使用GetPixel / SetPixel并对位图使用不安全的访问方法以获得某种速度。

System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

然后使用图形实例。如果我记得,修改图形对象会修改位图。

答案 1 :(得分:0)

首先你应该创建位图,然后从这个位图创建图形,使用图形,然后保存(或使用它)位图。

您的代码将是这样的:

using (Bitmap image = new Bitmap(X, Y))
{
    using (Graphics gr = Graphics.FromImage(image))
    {
        // work with graphics, Draw objects
    }
    image.Save("YourPathToFile"); // Or GetPixel, if you want
}

您的代码无法正常工作,因为Bitmap的构造函数仅获取图形用于解析。 MSDN告诉Initializes a new instance of the Bitmap class with the specified size and with the resolution of the specified Graphics object.

答案 2 :(得分:0)

(很晚,但......)

你试过吗

var bmp = System.Drawing.Bitmap.FromHbitmap(gr.GetHdc());

然后你可以从bmp读取像素。