PictureBox DrawToBitmap抛出异常无效参数

时间:2015-07-16 06:41:17

标签: c# image winforms bitmap picturebox

我正在尝试捕获屏幕并将捕获的图像分配给PictureBox,使用Paint事件进行绘制,然后将其绘制到其他Bitmap进行保存。但是,当我这样做时,我得到例外“Invalid parameter”

var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                             Screen.PrimaryScreen.Bounds.Y,
                             0,
                             0,
                             bmpScreenshot.Size,
                             CopyPixelOperation.SourceCopy);

// Assign the screenshot to the image
pbScreen.Image = bmpScreenshot;

// Do some drawing here  
//....
//....

// Draw that to bitmap so I can save it with edits
Bitmap bmp = new Bitmap(pbScreen.Image);
GraphicsUnit test = GraphicsUnit.Display;
var rect = Rectangle.Round(pbScreen.Image.GetBounds(ref test));
pbScreen.DrawToBitmap(bmp, rect); // <-- Exception happens here

编辑:完全例外

System.ArgumentException: Parameter is not valid.
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
   at System.Windows.Forms.Control.DrawToBitmap(Bitmap bitmap, Rectangle targetBounds)
   at app22.fgrab.CaptureScreen() in D:\CProgramming\app22\app22\Form1.cs:line 98
   at app22.fgrab.Action() in D:\CProgramming\app22\app22\Form1.cs:line 105
   at app22.fgrab.DoAction(HotKeyEventArgs e) in D:\CProgramming\app22\app22\Form1.cs:line 67
   at app22.fgrab.HotkeyManager_HotKeyPressed(Object sender, HotKeyEventArgs e) in D:\CProgramming\app22\app22\Form1.cs:line 59
   at app22.HotkeyManager.OnHotKeyPressed(HotKeyEventArgs e) in D:\CProgramming\app22\app22\HotkeyManager.cs:line 48
   at app22.fgrab.WndProc(Message& m) in D:\CProgramming\app22\app22\Form1.cs:line 122

1 个答案:

答案 0 :(得分:0)

GDI +错误消息的精彩世界。这条消息意味着很多。

我发现您的代码存在一个大问题:实现IDisposable的任何类型实际上都没有被处理掉。这将是BitmapGraphics

你有两种可能性来处置它们:

  1. using声明中使用它们:

    using(var bmpScreenshot = new Bitmap(...)) {
        ...
    }
    

    当然,不只是bmpScreenshot,而是实现IDisposable类型的每个变量。

  2. 当您不再需要时,请使用.Dispose()自行处理。

  3. 为什么GC没有启动?
    因为System.Drawing中的位图和其他类型使用非托管资源!