保存图片框的图像

Saving the image of a picturebox

所以我有这个代码:

Private Sub button28_Click(sender As Object, e As EventArgs) Handles button28.Click
    Dim bounds As Rectangle
    Dim screenshot As System.Drawing.Bitmap
    Dim graph As Graphics
    bounds = PicOuterBorder.Bounds
    screenshot = New System.Drawing.Bitmap(bounds.Width, bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
    graph = Graphics.FromImage(screenshot)
    graph.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy)
    picFinal.Image = screenshot
    'this takes a screenshot
End Sub 

PicOuterBorder 是我表格上的一个图片框。 PicFinal 是另一个显示图片框。但是这段代码让我得到了这个: 这基本上是一个 window 的屏幕截图,从我的屏幕原点开始,大小为 PicOuterBorder。但是,Me.Bounds 而不是 PicOuterBorder.Bounds 可以正常工作并获得我的表单的完美屏幕截图。我希望 picFinal 只截取 PicOuterBorder

将您的代码调整为如下内容:

Public Sub SaveImage(filename As String, image As Image, Encoder As ImageCodecInfo, EncParam As EncoderParameter)

Dim path As String = System.IO.Path.Combine(My.Application.Info.DirectoryPath, filename & ".jpg")
Dim mySource As New Bitmap(image.Width, image.Height)
Dim grfx As Graphics = Graphics.FromImage(mySource)
grfx.DrawImageUnscaled(image, Point.Empty)
grfx.Dispose()
mySource.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg)
mySource.Dispose()

End Sub

试试下面的代码。您必须使用 PointToScreen 将控件坐标映射到屏幕坐标。我已将 PicOuterBorder 放置在面板 PanelPicture 内。 PanelPicture 没有任何边框,而 PicOuterBorder 可以有任何类型的边框样式。下面的代码获取面板的快照。

Private Sub button28_Click(sender As Object, e As EventArgs) Handles button28.Click
    Dim graph As Graphics = Nothing
    Dim bounds As Rectangle = Nothing
    Dim screenshot As System.Drawing.Bitmap

    Dim location As Drawing.Point = PanelPicture.PointToScreen(Drawing.Point.Empty)
    screenshot = New System.Drawing.Bitmap(PanelPicture.Width, PanelPicture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
    graph = Graphics.FromImage(screenshot)
    graph.CopyFromScreen(location.X, location.Y, 0, 0, PanelPicture.Size, CopyPixelOperation.SourceCopy)
    picFinal.Image = screenshot

    graph.Dispose()
End Sub