我有一列将图片存储在MS Access数据库中。在该列中,右键单击它并插入文件中的图片对象 并在列中显示“包装”。
想法是将图片从文件上传到访问数据库的“ pic”列中,并使用“ querypic”表适配器查询,参数为“ comboname.text”,以返回图片并将其作为二进制存储在数组的字节中
但是当我将其转换为图像时出现错误
System.ArgumentException:'参数无效。
我检查了我的b()字节数组,结果为{length = 40276} 有人可以帮我吗?
Private Sub cmdSelect_Click(sender As Object, e As EventArgs) Handles cmdSelect.Click
Dim facultytabeladapt As New CSE_DEPTDataSetTableAdapters.FacultyTableAdapter
Dim b() As Byte
Dim s As String
b = facultytabeladapt.querypic(ComboName.Text)
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim imgc As New ImageConverter
Dim imgpic As Image = CType(imgc.ConvertFrom(b), Image) 'it has error "System.ArgumentException: 'Parameter is not valid."
Return imgpic
End Function
这可能是由于我直接上传以访问而不是RAW二进制文件的图片中的OLEDB对象
编辑: querypic是
SELECT pic
FROM Faculty
WHERE (faculty_name = ?)
其中faculty_name是comboname.text
答案 0 :(得分:1)
如果已经有字节数组,请从字节数组创建一个内存流,然后从该流创建一个映像。不要忘记添加Import System.IO
来使用MemoryStream
类。
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
完整代码:
Imports System.IO
Imports System.Drawing.Imaging
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim b() As Byte
b = ReadImage(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) & "\test.png")
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
''' <summary>
''' This function reads a file and returns a byte array
''' </summary>
''' <param name="file">A file in full path name</param>
''' <returns>A byte array of the image</returns>
Private Function ReadImage(file As String) As Byte()
Dim image As Image = Image.FromFile(file) ' read image from file
Dim ms As New MemoryStream ' prepare a memory stream
image.Save(ms, ImageFormat.Png) ' save the image into memory stream
Return ms.ToArray() ' return byte array
End Function
End Class