开发者

How to create Bitmap object from a Graphics object?

How to create Bitmap object from a Graphics object ? I would like to read pixels from my Graphics object. for example, like, System.Drawing.BitMap.GetPixel().

I am trying to find out empty area (all white, or of any colour) inside a pdf document, to write some graphics / image. I have tr开发者_运维百科ied like this, but it is not working. why the following code is not working as expected ?

//
// 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();

( posting this question again in .net-only context, removing other library dependencies )


Ideally you want to avoid GetPixel/SetPixel and use unsafe access methods to the bitmap for some speed.

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

then use the graphics instance. If I recall, modifying the graphics object modifies the bitmap.


Firstly you should create bitmap, then create graphics from this bitmap, work with graphics and after that save (or work with it) bitmap.

Your code will be like this:

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
}

Your code is not working as you excepted because constructor of Bitmap gets Graphics only for resolution. MSDN tells Initializes a new instance of the Bitmap class with the specified size and with the resolution of the specified Graphics object.


(very late, but...)

Have you tried

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

Then you can read pixels from bmp.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜