【发布时间】:2018-02-26 00:24:59
【问题描述】:
我使用我的 WPF 应用程序中的代码将图像插入到 .mdb 数据库中:
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & GetCurrentDirectory() & "\Data\rctts.mdb;Jet OLEDB:Database Password=arn33423342;")
con.Open()
Dim cmd As New OleDbCommand("Insert into recents(Uname,Pic,Email)values(@uname,@pic,@email)", con)
image1.Source = New BitmapImage(New Uri("D:\logo.png"))
Dim buffer As Byte()
Dim bitmap = TryCast(image1.Source, BitmapSource)
Dim encoder = New PngBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(bitmap))
Using stream = New MemoryStream()
encoder.Save(stream)
buffer = stream.ToArray()
End Using
cmd.Parameters.AddWithValue("@pic", buffer)
Pic 列或单元格的数据类型是 OLE 对象...无论如何,插入数据后,我打开我的数据库,我看到添加了一条新记录,但 Pic 列的值是 @987654324 @.Anyway,然后我继续在我的 wpf 应用程序中检索图像。我使用了这个代码?
Dim cmd As New OleDbCommand("Select * from recents", con)
Dim table As New DataTable
Dim adap As New OleDbDataAdapter(cmd)
adap.Fill(table)
If table.Rows.Count <= 0 Then
Else
For Each row In table.Rows
recentbtn.Image.ImageSource = BytesToImage(CType(row(1), Byte()))
recentbtn.Names.Text = table.Rows(0)(0).ToString
AddHandler recentbtn.MouseDown, AddressOf recentbtn_mousedow
RecentsList.stp.Children.Add(recentbtn)
Next
End If
loadingrecents.Visibility = Visibility.Hidden
End Sub
Private Shared Function BytesToImage(ByVal bytes As Byte()) As BitmapImage
Dim bm = New BitmapImage()
Using stream As MemoryStream = New MemoryStream(bytes)
stream.Position = 0
stream.Seek(0, SeekOrigin.Begin)
bm.BeginInit()
bm.StreamSource = stream
bm.CreateOptions = BitmapCreateOptions.PreservePixelFormat
bm.CacheOption = BitmapCacheOption.OnLoad
bm.EndInit()
End Using
Return bm
End Function
但它返回错误:找不到适合完成操作的成像组件
【问题讨论】:
-
调试你的代码并确保你得到一个填充的字节数组。
-
@TnTinMn,我不明白,你能解释一下吗?
标签: wpf vb.net image byte memorystream