我需要将应用程序表单的图像保存到图片文件中,如jpeg、bmp或png等。
互联网上的许多来源给出了这个或类似的代码示例,用于捕捉表单的图像:
Private Function TakeScreenShot(ByVal Control As Control) As Bitmap
Dim tmpImg As New Bitmap(Control.Width, Control.Height)
Using g As Graphics = Graphics.FromImage(tmpImg)
g.CopyFromScreen(Control.PointToScreen(New Point(0, 0)), New Point(0, 0), New Size(Control.Width, Control.Height))
End Using
Return tmpImg
End Function
这是为了保存由该代码捕获的表单的图像:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TakeScreenShot(Me).Save("c:My FolderScreenshot.png", System.Drawing.Imaging.ImageFormat.Png)
End Sub
捕获表单图像的代码似乎可以工作(不会导致错误(,但将图像保存到文件的代码行会出现以下错误:
>中发生类型为"System.Runtime.InteropServices.ExternalException"的未处理异常;System.Drawing.dllGDI+中出现一般性错误。
我尝试过代码的变体,但在所有情况下,将图像保存到文件的语句
.Save("c:My FolderScreenshot.png", System.Drawing.Imaging.ImageFormat.Png)
总是给出异常错误。我做错了什么?有什么建议吗?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim tmpImg As Bitmap = TakeScreenShot(Me)
Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
path = IO.Path.Combine(path, "Screen.png")
tmpImg.Save(path, System.Drawing.Imaging.ImageFormat.Png)
End Sub
您正在从屏幕(在Form
的边界内(获取矩形,而不是Form
屏幕截图。但是,您不必直接从tmpImage
保存(因为它尚未发布(,而是从该图像的源副本保存。下面的代码显示了如何(方法之一(:
Using final As Bitmap = New Bitmap(TakeScreenShot(Me))
final.Save("C:My FolderScreenshot.png")
End Using