Unable to cast object of type 'System.String' to type 'System.Byte[]'. Exception
Code (VB.NET)
Dim ofDlg As New OpenFileDialog()
'Reading a picture from disk and put it in a bytearray
Using fo As New OpenFileDialog With
{.Filter = "JpG (*.jpg)|*.jpg|Gif (*.gif)|*.gif|All files (*.*)|*.*"}
If fo.ShowDialog = DialogResult.OK Then
tmpFileName = fo.FileName
Me.Label35.Text = tmpFileName
Dim fs As New IO.FileStream(fo.FileName, _
IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
Dim byteArray = br.ReadBytes(CInt(fs.Length))
br.Close()
Dim ms As New IO.MemoryStream(byteArray)
Me.PictureBox1.Image = Image.FromStream(ms)
End If
End Using
Code (VB.NET)
Private Sub ShowImage()
Dim sqlImage As String
sqlImage = "SELECT PICTURE FROM land"
sqlImage &= " WHERE LANDID ='1'"
With Conn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = strConnstring
.Open()
End With
da = New SqlDataAdapter(sqlImage, Conn)
da.Fill(ds, "land")
da.SelectCommand.CommandText = sqlImage
da.Fill(ds, "land")
If ds.Tables("land").Rows.Count <> 0 Then
IsFindImage = True
CurrentImage = CType(ds.Tables("land").Rows(0).Item("PICTURE"), Byte())
Dim ms As New MemoryStream(CurrentImage, True)
PictureBox1.Image = Image.FromStream(ms)
Else
IsFindImage = False
End If
End Sub
Tag : .NET, Ms SQL Server 2008, Win (Windows App), VB.NET, VS 2012 (.NET 4.x)
Private tmpFileName As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Reading a picture from disk and put it in a bytearray
Using fo As New OpenFileDialog With
{.Filter = "JpG (*.jpg)|*.jpg|Gif (*.gif)|*.gif|All files (*.*)|*.*"}
If fo.ShowDialog = DialogResult.OK Then
tmpFileName = fo.FileName
Call LoadImage(tmpFileName)
End If
End Using
End Sub
Private Sub LoadImage(ByRef picturePath As String)
Me.Label2.Text = tmpFileName
Dim fs As New IO.FileStream(picturePath, _
IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
Dim byteArray = br.ReadBytes(CInt(fs.Length))
br.Close()
'just to show the sample without a fileread error
Dim ms As New IO.MemoryStream(byteArray)
Me.PictureBox1.Image = Image.FromStream(ms)
End Sub
Private Sub ShowImage()
Dim sqlImage As String
sqlImage = "SELECT PICTURE FROM land"
sqlImage &= " WHERE LANDID ='1'"
With Conn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = strConnstring
.Open()
End With
da = New SqlDataAdapter(sqlImage, Conn)
da.Fill(ds, "land")
da.SelectCommand.CommandText = sqlImage
da.Fill(ds, "land")
If ds.Tables("land").Rows.Count <> 0 Then
IsFindImage = True
Call LoadImage(ds.Tables("land").Rows(0).Item("PICTURE"))
Else
IsFindImage = False
End If
End Sub