问题
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 )
回答1:
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.
回答2:
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.
回答3:
(very late, but...)
Have you tried
var bmp = System.Drawing.Bitmap.FromHbitmap(gr.GetHdc());
Then you can read pixels from bmp
.
来源:https://stackoverflow.com/questions/3021902/how-to-create-bitmap-object-from-a-graphics-object