将Graphics对象转换为Bitmap
我的图形对象确实存在以下问题。
编辑:
我有一个picturebox_image (imageRxTx) ,这是一个来自相机的实时流。 我在绘制事件中所做的是在图像imageRxTx上绘制一些线条(未在下面的代码中显示)。 到目前为止这没有问题。
现在我需要检查imageRxTx中的圆圈,因此我必须使用需要Bitmap作为参数的方法ProcessImage() 。 不幸的是我没有Bitmap图像,而是我的imageRxTx的句柄(hDC) 。
问题 :如何从我的图形对象中获取imageRxTx并将其“转换”为我需要在方法ProcessImage(位图位图)中使用的位图图像 ? 需要在paint-event中连续调用此方法,以便检查我的相机的实时流(imageRxTx)。
这是我的代码:
private void imageRxTx_paint(object sender, PaintEventArgs e) { var settings = new Settings(); // Create a local version of the graphics object for the PictureBox. Graphics Draw = e.Graphics; IntPtr hDC = Draw.GetHdc(); // Get a handle to image_RxTx. Draw.ReleaseHdc(hDC); // Release image_RxTx handle. //Here I need to send the picturebox_image 'image_RxTx' to ProcessImage as Bitmap AForge.Point center = ProcessImage( ?....? ); } // Check for circles in the bitmap-image private AForge.Point ProcessImage(Bitmap bitmap) { //at this point I should read the picturebox_image 'image_RxTx' ...
video图像在此处更新:
private void timer1_Elapsed(object sender, EventArgs e) { // If Live and captured image has changed then update the window if (PIXCI_LIVE && LastCapturedField != pxd_capturedFieldCount(1)) { LastCapturedField = pxd_capturedFieldCount(1); image_RxTx.Invalidate(); } }
正如标题所暗示的那样,你的主要问题是关于Graphics
对象是什么的(常见的)错误概念。
到目前为止,我可以毫无问题地绘制到我的图形对象
-
没有! “
Graphics
”对象不包含任何图形。 它只是用于将图形绘制到相关Bitmap
上的工具 。 所以你根本没有绘制到Graphics
对象上; 你使用它绘制到imageRxTx
,无论是什么,可能是一些Control
或Form
的表面.. -
这一行使用了
Bitmap
构造函数常常令人困惑但相当无用的格式:
Bitmap bmp = new Bitmap(image_RxTx.Width, image_RxTx.Height, Draw);
最后一个参数是什么都没做; 它唯一的function是复制Dpi
设置。 特别是它不会克隆或复制来自’Draw’的任何内容,正如您现在所知,它仍然没有Graphics
对象,也没有任何其他设置。 所以是的,之后bmp Bitmap
仍然是空的。
如果要绘制到bmp
,则需要使用实际绑定到它的Graphics
对象:
using (Graphics G = Graphics.FromImage(bmp) { // draw now.. // to draw an Image img onto the Bitmap use G.DrawImage(img, ...); // with the right params for source and destination! }
这些都不应该发生在Paint
事件中! 但是所有准备代码都不清楚你真正想做什么。 您应该解释一下图纸的来源是什么,目标是什么!
如果你想把你在 image_RxTx
绘制的东西放到一个Bitmap
你可以在外面使用这个方法(!) Paint
事件:
Bitmap bmp = new Bitmap(image_RxTx.Width, image_RxTx.Height); image_RxTx.DrawToBitmap(bmp, image_RxTx.ClientRectangle);
这将使用 Paint
事件将控件绘制到Bitmap
。 不是结果包括整个 PictureBox
: BackgroundImage
, Image
和表面绘图!
更新 :要获取PictureBox
的组合内容,即它的Image
和绘制到表面上的内容,您应该在Timer
的Tick
事件中使用上面的代码(最后2行) 或者在该行之后使用触发Paint
事件。 (你没有告诉我们这是怎么发生的。)你不能将它实际放在Paint
事件本身,因为它将使用Paint
事件,因此会导致无限循环!
Graphics.CopyFromScreen
方法可能就是你要找的东西。
var rect = myControl.DisplayRectangle; var destBitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format24bppRgb); using (var gr = Graphics.FromImage(destBitmap)) { gr.CopyFromScreen(myControl.PointToScreen(new Point(0, 0)), new Point(0, 0), rect.Size); }