使用Access& amp;存储/检索图像VB.NET 2012

时间:2014-06-20 21:40:22

标签: vb.net image ms-access

VB.NET 2012

我有一个图片,一个mdb文件,头疼......

我创建了一个表,该表将包含一个路径字段,名称字段和对象字段,用于在Access中存储图像。很容易执行:

CREATE TABLE DATATABLE (FilePath CHAR, FileName CHAR, FileObject LONGBINARY)

我现在的问题?如何将图像放入该表中以及从该表中取出图像。这似乎应该很容易完成 - 但我一直在用过时的Append / GetChunk方法,WriteBLOBToFile方法,以及其他所有方法敲打我的头。谷歌通常是我的朋友,但今天我得到的帮助却无法发挥作用。

那里的任何人都有办法将图像放入上述表格中吗?这看起来应该是直截了当的。

并且请 - 尽管我宁愿将图像存储在文件系统而不是这个,规范要求在Access中存储图像。没办法解决它。感谢您对此的任何帮助!!!

谢谢,

杰森

1 个答案:

答案 0 :(得分:0)

根据建议,如果您不需要存储数据以便可以在Access中将其作为图像进行访问,则可以使用MemoryStream作为中介。

Private Sub SaveImage(picture As Image, id As Integer)
    Dim connection As New OleDbConnection("connection string here")
    Dim command As New OleDbCommand("UPDATE MyTable SET Picture = @Picture WHERE ID = @ID", connection)

    'Create an empty stream in memory.
    Using stream As New IO.MemoryStream
        'Fill the stream with the binary data from the Image.
        picture.Save(stream, Imaging.ImageFormat.Jpeg)

        'Get an array of Bytes from the stream and assign to the parameter.
        command.Parameters.AddWithValue("@Picture", stream.GetBuffer())
    End Using

    command.Parameters.AddWithValue("@ID", id)

    connection.Open()
    command.ExecuteNonQuery()
    connection.Close()
End Sub

Private Function LoadImage(id As Integer) As Image
    Dim connection As New OleDbConnection("connection string here")
    Dim command As New OleDbCommand("SELECT Picture FROM MyTable WHERE ID = @ID", connection)

    command.Parameters.AddWithValue("@ID", id)

    connection.Open()

    Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())

    connection.Close()

    Dim picture As Image

    'Create a stream in memory containing the bytes that comprise the image.
    Using stream As New IO.MemoryStream(pictureData)
        'Read the stream and create an Image object from the data.
        picture = Image.FromStream(stream)
    End Using

    Return picture
End Function