如何将图像从一个图片框传输到另一个图片框? VB.NET 和 SQL

Posted

技术标签:

【中文标题】如何将图像从一个图片框传输到另一个图片框? VB.NET 和 SQL【英文标题】:How can I Transfer an image from one picturebox to another? VB.NET & SQL 【发布时间】:2022-01-02 13:13:21 【问题描述】:

我正在尝试做一个登录系统,在其中我将凭据和所需的个人资料图片图像存储在访问数据库中。期望的结果是,当登录匹配时,表单 1 关闭并打开表单 2,保存的图像加载在角落。

我试过这样做

表格1代码:

Imports System.Data.OleDb
Imports System.IO
Public Class Form1

    Private PictureFormat As String

    Private Sub FillPictureBoxFromFile()
        With OpenFileDialog1
            .Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
            .RestoreDirectory = True
            .Title = "Select a file to open"
            If .ShowDialog = DialogResult.OK Then
                PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
            End If
            PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
        End With
    End Sub

    Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\Login Fase 3 Final\Login Fase 3 Final\bin\Release\DBLoginPic.mdb"

    Private Sub saveimage()
        Dim arrimage() As Byte
        Using mstream As New System.IO.MemoryStream
            If PictureFormat.ToLower = ".png" Then
                PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
            ElseIf PictureFormat.ToLower = ".jpg" Then
                PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
            End If
            arrimage = mstream.GetBuffer()
            Dim Filesize As Long
            Filesize = mstream.Length
        End Using
        Using con As New OleDbConnection(cnStr),
                cmd As New OleDbCommand("Insert into TBLoginPic (Imagen) Values (@Imagen)", con)
            With cmd
                .Parameters.Add("@Imagen", OleDbType.Binary).Value = arrimage
                '.Parameters.Add("@Nombre", OleDbType.VarChar).Value = TextBox1.Text
                con.Open()
                .ExecuteNonQuery()
            End With
        End Using
    End Sub

    Private Function GetDataByName(name As String) As DataTable
        Dim dt As New DataTable
        Using conn As New OleDb.OleDbConnection(cnStr),
                cmd As New OleDbCommand("Select * from TBLoginPic where Usuario= @Buscar", conn)
            cmd.Parameters.Add("@Buscar", OleDbType.VarChar).Value = TBusuario.Text
            conn.Open()
            Using reader = cmd.ExecuteReader
                dt.Load(reader)
            End Using
        End Using
        Return dt
    End Function


    Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click

    End Sub

    Private Sub TBusuario_TextChanged(sender As Object, e As EventArgs) Handles TBusuario.TextChanged

    End Sub

    Private Sub TBcontraseña_TextChanged(sender As Object, e As EventArgs) Handles TBcontraseña.TextChanged

    End Sub

    Private Sub BtnLoguearse_Click(sender As Object, e As EventArgs) Handles BtnLoguearse.Click
        If Me.TBLoginPicTableAdapter.BuscarDatos(Me.DBLoginPicDataSet.TBLoginPic, TBusuario.Text, TBcontraseña.Text) Then

            Dim dt As DataTable
            Try
                dt = GetDataByName(TBusuario.Text)
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Exit Sub
            End Try

            TBusuario.Text = dt(0)("Usuario").ToString
            Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
            Dim mstream As New System.IO.MemoryStream(arrimage)
            PictureBox1.Image = Image.FromStream(mstream)

            Form2.Show()
            _selectedImage = PictureBox1.Image
            Me.Close()
        Else
            MsgBox("Datos Erroneos")
        End If
    End Sub

    Private Sub BtnRegistrarse_Click(sender As Object, e As EventArgs) Handles BtnRegistrarse.Click


        Me.TBLoginPicBindingSource.AddNew()
        Me.TBLoginPicBindingSource.EndEdit()
        Me.TBLoginPicTableAdapter.Update(Me.DBLoginPicDataSet)


        Try
            saveimage()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Exit Sub
        End Try
        MsgBox("Image has been saved in the database")

    End Sub

    Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
        FillPictureBoxFromFile()
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
        Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)



    End Sub

    Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBLoginPicBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)

    End Sub
End Class

表格2代码:

Module imagen
    Public _selectedImage As Image
    Public ReadOnly Property SelectedImage As Image
        Get
            Return _selectedImage
        End Get
    End Property
End Module

Public Class Form2



    Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.TBLoginPicBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)

    End Sub

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
        Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)
        _selectedImage = PBPerfil.Image

    End Sub

    Public Sub PBPerfil_Click(sender As Object, e As EventArgs) Handles PBPerfil.Click

    End Sub
End Class

得到这个错误

System.InvalidCastException:'无法将'System.DBNull'类型的对象转换为'System.Byte[]'类型。'

This is how form 1 looks like

This is how form 2 looks like

This is how my database looks like (don't worry there is not any personal info here))

This is where I try to send it from form 1 to 2

This is how I'm trying to receive it on form 2

有什么建议可以让我做得更好吗?

【问题讨论】:

【参考方案1】:

您需要检查空值。如果图像列中没有数据,则在您尝试对其进行操作时会出错。如果数据库中不存在任何图像,我建议您选择要显示的默认图像。

    If dt(0)("Usuario") IsNot Nothing OrElse Not IsDBNull(dt(0)("Usuario")) Then
        TBusuario.Text = dt(0)("Usuario").ToString
        Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
        Dim mstream As New System.IO.MemoryStream(arrimage)
        PictureBox1.Image = Image.FromStream(mstream)
    Else
        PictureBox1.Image = Image.FromFile("DefaultImage.png")
    End If

【讨论】:

如何添加这样的图像?我是否需要放置类似于这样的连接字符串的路径:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\Login Fase 3 Final\Login Fase 3 Final\bin \Release\DBLoginPic.mdb。还是我只是在那里放一个文件路径?还是有其他方法?

以上是关于如何将图像从一个图片框传输到另一个图片框? VB.NET 和 SQL的主要内容,如果未能解决你的问题,请参考以下文章

如何将 wmf 文件动态分配给图片框

vb中图片框如何清除里面的所有内容?

VB 如何判断两个图片框中的图像是相同或相似

将变量从一个图片框复制到另一个图片框而不会相互更改

图片不会在图片框中更改,vb.net

从 Excel 到 vb.net Picturebox 的图像