使用功能显示图像

时间:2015-05-17 05:52:56

标签: mysql vb.net function

我是VB的新手。 NET所以请耐心等待。在下面的代码中,我的主窗体中有一个图片框,我希望所选的查询profile_picture显示在图片框中,但我不知道该函数应该返回什么

Public Sub ShowPicture(ByVal username As String)
    user = username
    Dim dsSearch As DataSet
    ModuleQuery.Showpic(username)

    Dim dSearch As Byte() = DirectCast(dr("Photo"), Byte())
    Dim ms As New MemoryStream(dsSearch)
    prof_pic.Image = Image.FromStream(ms)

End Sub

这是一个包含所有SELECT查询的模块,因此它不会混乱。 我想调用一个函数,但我不知道要返回什么,以便我可以显示图像

Public Function Showpic(ByVal user As String)
    Dim FunctionErrorState As Boolean = False
    Dim InsertError As Boolean = False
    Dim CloseError As Boolean = False

    Dim dsData As New DataSet
    Dim bite As Byte()
    Try
        openDB()
        'MyADOConnection.Open()


        Dim myQuery As String = "SELECT profile_picture FROM coa.register WHERE username = '" & user & "'"

        Dim myCommand As New MySql.Data.MySqlClient.MySqlCommand(myQuery)

        dr = myCommand.ExecuteReader

        bite = DirectCast(dr("Photo"), Byte())


    Catch ex As MySql.Data.MySqlClient.MySqlException
        InsertError = True


    End Try
    Try
        MyADOConnection.Close()
    Catch exclose As MySql.Data.MySqlClient.MySqlException
        CloseError = True

    End Try
    If InsertError Then
        FunctionErrorState = True
    End If

    Return bite 'I just put something random here since I don't know what to retun
End Function

1 个答案:

答案 0 :(得分:0)

在我看来,图像被存储为数据库中的字节数组。您(我猜错了)您使用bite = DirectCast(dr("Photo"), Byte())函数中的ShowPic命令从数据库中读取此数组。字节数组只是内存中的一大块数据,稍后您可以使用MemoryStream进行查询。

因此,您的ShowPic函数(更多是GetPic函数;-)应该返回Byte()

Public Function Showpic(ByVal user As String) As Byte()

您应该使用bite

初始化Nothing
Dim bite As Byte() = Nothing

这样一来,如果发生错误,那么数组就没什么了,你可以检查一下。

为了将包含原始图像数据的字节数组转换为图像,您可以正确使用MemoryStreamImage.FromStream方法。 .NET中的I / O大部分都使用流。它们只是一种从某些来源持续提供数据的方法。在这种情况下,源只是内存,特别是从数据库中获取的字节数组。

但是你永远不会使用那个Byte数组。将ShowPic函数的结果分配给变量,以便使用它:

Public Sub ShowPicture(ByVal username As String)
    user = username
    Dim ImageData As Byte() = ModuleQuery.Showpic(username)
    If ImageData IsNot Nothing Then
        Using ms As New MemoryStream(ImageData)
            prof_pic.Image = Image.FromStream(ms)
        End Using
    Else
        'Your function returned nothing, so an error occured.
        'This is a very crude way of error handling, since you never
        'see the error in the first place, which makes debugging a
        'nightmare. There are better ways, out of scope of this answer.

        MessageBox.Show("No image retrieved due to an error :(")
    End If
End Sub

这样您就可以从GetPic中的数据库中检索图像数据(再次将其重命名为GetImageDataShowPic或其他内容)并将其原始数据返回到{{1}解码并显示它的方法。