3

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 tried 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 )

vi.su.
  • 685
  • 2
  • 9
  • 19

3 Answers3

0

(very late, but...)

Have you tried

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

Then you can read pixels from bmp.

heltonbiker
  • 26,657
  • 28
  • 137
  • 252
0

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.

MaLio
  • 2,498
  • 16
  • 23
  • thanks for your response, MaLio. please find my comment (in response to Belousov Pavel) above. – vi.su. Jun 14 '10 at 05:20
0

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.

Pavel Belousov
  • 1,848
  • 2
  • 14
  • 22
  • thanks for your response, Belousov. -- I already have a graphics object, constructed from pdf (and, I don't have a corresponding bitmap object, because rendering is not my pdf library's interest). I just want to read pixels from it, and I don't want to write / draw to it. I need bitmap object to read pixels, so I am trying to construct bitmap object from graphics object I have. -- While writing to System.Drawing.Graphics object is so easy, reading pixels from it made intentionally impossible. – vi.su. Jun 14 '10 at 05:15