-1

Thanks to one of your old questions, I started this code:

Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String

fd.Title = "Please select an image"
fd.InitialDirectory = "C:\Users\"
fd.Filter = "PNG Images (*.png*)|*.png*|JPG Images (*.jpg*)|*.jpg*|JPEG Images (*.jpeg*)|*.jpeg*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
    strFileName = fd.FileName

    Dim ImageTest As Image
    ImageTest = fd.FileName

    PictureBox1.Image = ImageTest
End If

Except that ImageTest is not functional. It gives me the error:

Cannot convert String to Image.

How do I get the user to select a personal image with an OpenFileDialog?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Loud
  • 1
  • 1

2 Answers2

0

The error is clear. You are taking the image filename (a string) and pretend it to be an image loaded with its data bytes. This is not correct and the compiler cannot let you go on.

The correct way is

If fd.ShowDialog() = DialogResult.OK Then
    strFileName = fd.FileName
    Dim ImageTest As Image = Image.FromFile(strFileName)
    PictureBox1.Image = ImageTest
End If
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Use as follows:

Sub AddImage()
    Using fd As OpenFileDialog = New OpenFileDialog()

        fd.Title = "Please select an image"
        fd.InitialDirectory = "C:\Users\"
        fd.Filter = "PNG Images (*.png*)|*.png*|JPG Images (*.jpg*)|*.jpg*|JPEG Images (*.jpeg*)|*.jpeg*|Tout les fichiers (*.*)|*.*"
        fd.FilterIndex = 2
        fd.RestoreDirectory = True

        If fd.ShowDialog() = DialogResult.OK Then
            Dim ImageTest As Image = Image.FromFile(fd.FileName)
            PictureBox1.Image = ImageTest
        End If

    End Using

End Sub
G3nt_M3caj
  • 2,497
  • 1
  • 14
  • 16