Vb.net 消失的图片盒图像

Vb.net 消失的图片盒图像,vb.net,image,Vb.net,Image,我成功地将图像从文件加载到VisualBasic的picturebox中。至少我是这么想的。我在代码中有一个msgbox,图片出现在图片盒中。拿出msgbox,不要拍照。有什么想法吗?谢谢 Private Sub DrawImageinSquarePanel(Panelname As PictureBox, ImageFile As String) g = Panelname.CreateGraphics() 'creates new graphics element in pa

我成功地将图像从文件加载到VisualBasic的picturebox中。至少我是这么想的。我在代码中有一个msgbox,图片出现在图片盒中。拿出msgbox,不要拍照。有什么想法吗?谢谢

    Private Sub DrawImageinSquarePanel(Panelname As PictureBox, ImageFile As String)
    g = Panelname.CreateGraphics() 'creates new graphics element in panel
    Dim newImage As Image = Image.FromFile(ImageFile) ' Create image.
    Dim SquareDim As Integer 'Size of longest dimension in source image

    If newImage.Width > newImage.Height Then
        SquareDim = newImage.Width
    Else
        SquareDim = newImage.Height
    End If

    MsgBox(Panelname.Width & "   " & Panelname.Height) 'the magic msgbox!!

    ' scale factor
    Dim imageAttr As New ImageAttributes
    imageAttr.SetGamma(Panelname.Width / SquareDim)
    Dim ScaleFactor As Single = Panelname.Width / SquareDim

    ' Create rectangle for source and destination image.
    Dim srcRect As New Rectangle(0, 0, newImage.Width, newImage.Height)
    Dim destRect As New Rectangle((Panelname.Width - newImage.Width * ScaleFactor) / 2, (Panelname.Height - newImage.Height * ScaleFactor) / 2, newImage.Width * ScaleFactor, newImage.Height * ScaleFactor)
    Dim units As GraphicsUnit = GraphicsUnit.Pixel

    ' Draw image to screen.
    g.DrawImage(newImage, destRect, srcRect, units)


End Sub
你的标题是“Picturebox”,但根本没有
Picturebox
。如果要在
图片盒中显示
图像
,请将
图像
对象指定给该
图片盒
图像
属性

不要使用GDI+在
面板上绘制,如果确实使用GDI+绘制,请不要调用
CreateGraphics
。始终在控件的
Paint
事件处理程序中绘制控件。图形消失的原因是每次
Paint
事件都会擦除所有图形。通过在
Paint
事件处理程序中绘制图形,可以确保每次都恢复绘制

如果要在显示图像之前修改图像,则应创建一个新的
位图
对象,使用GDI+将修改后的图像绘制到该对象上,然后将其指定给
PictureBox
图像
属性,例如

Using originalImage = Image.FromFile(filePath)
    Dim newImage As New Bitmap(originalImage.Width, originalImage.Height)

    Using g = Graphics.FromImage(newImage)
        g.DrawImage(originalImage, Point.Empty)
    End Using

    'Dispose the existing image if there is one.
    PictureBox1.Image?.Dispose()

    PictureBox1.Image = newImage
End Using

杰姆西林尼,非常感谢你的帮助。这个项目按照你的建议进行了很好的整合。如果这个答案解决了你的问题,请接受它,这样每个人都能看到。