我在访问文件中有一个图像,我想使用用户ID在另一个Windows窗体表单中检索并显示它。
保存图片的代码:
Dim img = PictureBox1. Image
Dim ms As New System.IO.MemoryStream
img.Save(ms, img.RawFormat)
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytImage = ms.ToArray()
ms.Close()
检索图像的代码:
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim userIdPro = Transfer.userIdPro
Dim query = ("SELECT Image FROM User_info WHERE ID = " & userIdPro & ";")
Dim ds As New DataSet
Dim dr As OleDb.OleDbDataReader
Dim cm = New OleDb.OleDbCommand(query, con)
dr = cm.ExecuteReader
While dr.Read()
Dim MyByte = dr.Item("Value")
Dim fs = New MemoryStream
fs.Write(MyByte, 0, MyByte.Length)
fs.Flush()
Dim MyImg = Image.FromStream(fs, True)
MyImg.Save(dr.Item("ID").ToString & ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg)
PictureBox1.Image = MyImg
fs.Close()
fs = Nothing
End While
con.Close()
End Sub
我无法将二进制数据带入dr
;它总是空的。
答案 0 :(得分:0)
我把您的代码调用了bytesToImage(...)函数。除非有理由保存图像,否则无需将其保存在本地。
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim userIdPro = Transfer.userIdPro
// Don't concatenate your parameters. This is a bad practice and
// exposes your application to SQL injection attacks. Use SQL
// parameters instead.
Dim query = ("SELECT Image FROM User_info WHERE ID = " & userIdPro & ";")
Dim ds As New DataSet
Dim dr As OleDb.OleDbDataReader
Dim cm = New OleDb.OleDbCommand(query, con)
dr = cm.ExecuteReader
While dr.Read()
Dim MyByte = dr.Item("Value")
Dim MyImg As Image
If MyByte IsNot Nothing Then
// You do not need to save it, just convert to an image
// type and set it to your PictureBox1 control.
MyImg = bytesToImage(MyByte)
PictureBox1.Image = MyImg
End If
End While
con.Close()
您的课程应将Image
属性设置为Byte()
<Table("User_info")>
Public Class User
Public Property Photo As Byte()
End Class
使用以下功能:
Public Function imageToBytes(ByVal imageIn As System.Drawing.Image) As Byte()
Dim ms As MemoryStream = New MemoryStream()
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Return ms.ToArray()
End Function
Public Function bytesToImage(ByVal byteArrayIn As Byte()) As Image
Dim ms As MemoryStream = New MemoryStream(byteArrayIn)
Dim returnImage As Image = Image.FromStream(ms)
Return returnImage
End Function
要将图像保存到数据库中:
Public Sub SaveImage()
Using context = New ProjectDb()
Dim user = New User() With {
.Id = Guid.NewGuid,
.Photo = imageToBytes(PictureBox1.Image)
}
context.Users.Add(user)
context.SaveChanges()
End Using
End Sub
要从数据库中获取图像:
Public Function GetImage(ByVal id As Guid) As Image
Using context = New ProjectDb()
Dim image As Image
Dim user As User = context.Users.FirstOrDefault(Function(x) x.Id = id)
If user IsNot Nothing Then
image = bytesToImage(user.Photo)
PictureBox2.Image = image
End If
End Using
End Function