vb.net 如何在VB.NET中从MySQL数据库检索图像到PictureBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26367297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:21:10  来源:igfitidea点击:

How to retrieve image from MySQL database to PictureBox in VB.NET

mysqlvb.net

提问by Sky Scraper

i'm trying to fetch an image into another form, all the text records from database are working fine, but when i add an image it has an error that says Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'., what am i missing out?

我正在尝试将图像提取到另一种形式,数据库中的所有文本记录都可以正常工作,但是当我添加图像时,它有一个错误提示Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.,我错过了什么?

this is the code of my 1st form:

这是我的第一种形式的代码:

Imports MySql.Data.MySqlClient

Public Class Form5

Dim a As OpenFileDialog = New OpenFileDialog
Public dc As Integer
Public ccfname As String
Public ccmname As String
Public cclname As String
Public ccpos As String
Public ccparty As String
Public photo As Image

Dim con As New MySqlConnection

Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim con As New MySqlConnection
    If con.State = ConnectionState.Closed Then
        con.ConnectionString = "server=localhost;user id=root;database=db;password=root"
        con.Open()
    End If
    LoadPeople()
End Sub

Public Sub LoadPeople()
    Dim sConnection As New MySqlConnection
    sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
    sConnection.Open()
    Dim sqlQuery As String = "SELECT * FROM candidate WHERE cfname<>'Select a Candidate' AND candidacy='Filed'"
    Dim sqlAdapter As New MySqlDataAdapter
    Dim sqlCommand As New MySqlCommand
    Dim TABLE As New DataTable
    Dim i As Integer


    With sqlCommand
        .CommandText = sqlQuery
        .Connection = sConnection
    End With

    With sqlAdapter
        .SelectCommand = sqlCommand
        .Fill(TABLE)
    End With

    LvPeople.Items.Clear()

    For i = 0 To TABLE.Rows.Count - 1
        With LvPeople
            .Items.Add(TABLE.Rows(i)("idn"))
            With .Items(.Items.Count - 1).SubItems
                .Add(AddFieldValue(TABLE.Rows(i), ("cpos")))
                .Add(AddFieldValue(TABLE.Rows(i), ("cfname")))
                .Add(AddFieldValue(TABLE.Rows(i), ("cmname")))
                .Add(AddFieldValue(TABLE.Rows(i), ("clname")))
                .Add(AddFieldValue(TABLE.Rows(i), ("cparty")))
            End With
        End With
    Next
End Sub

Private Function AddFieldValue(ByVal row As DataRow, ByVal fieldName As String) As String
    If Not DBNull.Value.Equals(row.Item(fieldName)) Then
        Return CStr(row.Item(fieldName))
    Else
        Return Nothing
    End If
End Function

Private Sub lvPeople_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles LvPeople.MouseClick
    dc = LvPeople.SelectedItems(0).Text
End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    If dc = Nothing Then
        MsgBox("Please choose a record to view.", MsgBoxStyle.Exclamation)
    Else

        Dim sqlCommand As New MySqlCommand
        con.ConnectionString = "server = localhost; user id = root; database = db; password = root"
        sqlCommand.Connection = con
        con.Open()
        Dim sqlQuery As String = "SELECT * FROM candidate WHERE idn = '" & LvPeople.SelectedItems(0).Text & "'"
        Dim sqlAdapter As New MySqlDataAdapter
        Dim sqlTabble As New DataTable

        With sqlCommand
            .CommandText = sqlQuery
            .Connection = con
            .ExecuteNonQuery()
        End With

        With sqlAdapter
            .SelectCommand = sqlCommand
            .Fill(sqlTabble)
        End With
        Form25.dc = LvPeople.SelectedItems(0).Text
        Form25.ccfname = sqlTabble.Rows(0)("cfname")
        Form25.ccmname = sqlTabble.Rows(0)("cmname")
        Form25.cclname = sqlTabble.Rows(0)("clname")
        Form25.ccpos = sqlTabble.Rows(0)("cpos")
        Form25.ccparty = sqlTabble.Rows(0)("cparty")
        Form25.photo = sqlTabble.Rows(0)("photo")
        Form25.ShowDialog()
        con.Close()

        dc = Nothing
    End If
End Sub

Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
    Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
    Dim Sql As String = "SELECT * FROM candidate WHERE idn='" & LvPeople.SelectedItems(0).Text & "'"
    Dim conn As New MySqlConnection(connstring)
    Dim cmd As New MySqlCommand(Sql, conn)
    Dim dr As MySqlDataReader = Nothing
    conn.Open()
    dr = cmd.ExecuteReader()
    dr.Read()
    Dim imagebytes As Byte() = CType(dr("photo"), Byte())
    Using ms As New IO.MemoryStream(imagebytes)
        PictureBox1.Image = Image.FromStream(ms)
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    End Using
    conn.Close()
End Sub

and this is my 2nd form which i was trying to fetch the image to.

这是我试图获取图像的第二个表单。

Imports MySql.Data.MySqlClient
Public Class Form25

Dim a As OpenFileDialog = New OpenFileDialog
Public sConnection As New MySqlConnection
Friend dc As Integer
Friend ccfname As String
Friend ccmname As String
Friend cclname As String
Friend ccpos As String
Friend ccparty As String
Friend photo As Image

Private Sub Form25_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If sConnection.State = ConnectionState.Closed Then
        sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
        sConnection.Open()
    End If
    Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
    Dim Sql As String = "SELECT * FROM candidate WHERE idn='" & Form5.LvPeople.SelectedItems(0).Text & "'"
    Dim conn As New MySqlConnection(connstring)
    Dim cmd As New MySqlCommand(Sql, conn)
    TextBox2.Text = ccfname
    TextBox3.Text = ccmname
    TextBox4.Text = cclname
    ComboBox1.Text = ccpos
    TextBox1.Text = ccparty
    PictureBox1.Image = photo
End Sub
End Class

the error points here:

错误点在这里:

Form25.dc = LvPeople.SelectedItems(0).Text
        Form25.ccfname = sqlTabble.Rows(0)("cfname")
        Form25.ccmname = sqlTabble.Rows(0)("cmname")
        Form25.cclname = sqlTabble.Rows(0)("clname")
        Form25.ccpos = sqlTabble.Rows(0)("cpos")
        Form25.ccparty = sqlTabble.Rows(0)("cparty")
        Form25.photo = sqlTabble.Rows(0)("photo") <<--------------HERE------|
        Form25.ShowDialog()
        con.Close()

this is from the first form.

这是从第一种形式。

采纳答案by InbetweenWeekends

This is what I use to do something similar. This would let you use:

这就是我用来做类似事情的方法。这将让您使用:

Form25.photo = Byte2Image(sqlTabble.Rows(0)("photo"))

You may need to do some explicit casting.

您可能需要进行一些显式转换。

Public Shared Function Byte2Image(ByVal byteArr() As Byte) As Drawing.Image

    Using ImageStream As New MemoryStream(byteArr)
        Dim newImage As Drawing.Image
        Try
            If byteArr.GetUpperBound(0) > 0 Then
                newImage = System.Drawing.Image.FromStream(ImageStream)
            Else
                newImage = Nothing
            End If
        Catch ex As Exception
            newImage = Nothing
        End Try
        Return newImage
    End Using

End Function