vb.net 如何将数据库中的图像添加到PictureBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6350516/
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-09 15:32:42  来源:igfitidea点击:

How to add image from database to PictureBox?

vb.netimagepicturebox

提问by ConfusedCoder

I am using this to get image bytes from the database

我正在使用它从数据库中获取图像字节

cmd.CommandText = "select imagedate from projectimages where imagename = '" + _
    ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"

Dim img As Object = cmd.ExecuteScalar()

Now how can I add this to PictureBox.image. I am having a lot of trouble retrieving the image and displaying it in the PictureBox.

现在我如何将它添加到 PictureBox.image。我在检索图像并将其显示在 PictureBox 中时遇到了很多麻烦。

The datatype is Image in sql database and i use this code to save image to db

数据类型是 sql 数据库中的图像,我使用此代码将图像保存到数据库

         Dim ms As New IO.MemoryStream

        If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

        End If
        If imageFilename.Contains("png") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
        End If
        If imageFilename.Contains("gif") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
        End If
        If imageFilename.Contains("bmp") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
        End If

        Dim bytes() As Byte = ms.ToArray
        Dim img As String = Convert.ToBase64String(bytes)


        Dim cmd As New OleDb.OleDbCommand("insert projectimages values('" + imageNameTemp + "','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)
        cmd.ExecuteNonQuery()

采纳答案by ConfusedCoder

After 5-6 hours of searching forums and blogs and everything i fond this... to save image to database

在搜索了 5-6 个小时的论坛和博客以及我喜欢的所有内容之后……将图像保存到数据库

1- datatype should be image in database

1-数据类型应该是数据库中的图像

Now add this code when storing image to the sql database

现在将图像存储到sql数据库时添加此代码

    OpenFileDialog1.ShowDialog()
    imageFilename = OpenFileDialog1.FileName
    Dim imageUpload As Image
    imageUpload = Image.FromFile(OpenFileDialog1.FileName)



    If imageFilename <> "" Then

        Dim imageNameTemp As String

        imageNameTemp = imageFilename

        While (imageNameTemp.Contains("\"))


            imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
        End While

        Dim ms As New IO.MemoryStream

        If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

        End If
        If imageFilename.Contains("png") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
        End If
        If imageFilename.Contains("gif") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
        End If
        If imageFilename.Contains("bmp") Then
            imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
        End If

        'Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageFilename + "',@BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)

        Dim b() As Byte = ms.ToArray()

        Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageNameTemp + "',@BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)

        cmd.Parameters.Add("@BLOBData", SqlDbType.Image, b.Length).Value = b
        '    Dim cmd As New SqlCommand("insert projectimages(imagename,imagedate,csvprojectref) values('imagma','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)

        cmd.ExecuteNonQuery()

        '  cmdTemp.Parameters.Add("@photo", SqlDbType.Image, b.Length).Value = b

    End If

And when to retrieve data to insert into picture box use this code...

何时检索数据以插入图片框使用此代码...

  cmd.CommandText = "select imagedate from projectimages where imagename = '" +      ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"


        cmd.Connection = con
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds, "projectimages")
        Dim c As Integer = ds.Tables(0).Rows.Count
        If c > 0 Then
            Dim bytBLOBData() As Byte = _
                ds.Tables(0).Rows(c - 1)("imagedate")
            Dim stmBLOBData As New MemoryStream(bytBLOBData)
            PictureBox1.Image = Image.FromStream(stmBLOBData)
        End If

回答by William Fenji

here's my code to show blob file to picturebox in vb.net. hope it helps

这是我在 vb.net 中向图片框显示 blob 文件的代码。希望能帮助到你

Dim connstring As String = "Database=pmk;data source=localhost;user id=root;password="
Dim Sql As String = "select * from mastermahasiswa where Nim='" & TextBox1.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("Foto"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
    PictureBox1.Image = Image.FromStream(ms)
    PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()

回答by Tammi

I was getting the parameter not valid error as well. To fix, I added a picturebox to my form that loads the image I'm copying to the SQL server as a background image. This statement seems to be key:

我也收到参数无效错误。为了解决这个问题,我在表单中添加了一个图片框,用于加载我正在复制到 SQL 服务器的图像作为背景图像。这句话似乎是关键:

PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)

It makes the actual upload take a lot longer, but I'm no longer getting the parameter error... I think because the pictures are actually valid images now.

它使实际上传需要更长的时间,但我不再收到参数错误......我想是因为图片现在实际上是有效的图像。

        SSScmd.CommandText = "INSERT INTO PreviewSlideshow (Name, Photo) VALUES (@name, @photo)"

        Dim p As New SqlParameter("@photo", SqlDbType.Image)

        For Each CurFile As IO.FileInfo In New IO.DirectoryInfo(sSourcePath).GetFiles

            If CurFile.Name = "Thumbs.db" Then
                'skip
            Else

                If CurFile.Extension = "jpg" Or CurFile.Extension = "png" Then

                    'show the image name on the form
                    ImageName.Text = CurFile.Name

                    SSScmd.Parameters.AddWithValue("@name", ImageName.Text)

                    Dim ms As New MemoryStream()

                    PictureBox1.BackgroundImage = Image.FromFile(sSourcePath & CurFile.Name)

                    PictureBox1.BackgroundImageLayout = ImageLayout.Stretch

                    PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)

                    Dim data As Byte() = ms.GetBuffer()

                    p.Value = data

                    SSScmd.Parameters.Add(p)

                    SSScmd.ExecuteNonQuery()

                    SSScmd.Parameters.Clear()



                End If
            End If

        Next

回答by Lance Roberts

Use a MemoryStream object as per Microsoft.

按照Microsoft使用 MemoryStream 对象。

回答by Bala R

Dim img As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
Dim ms as MemoryStream = New MemoryStream(img)
pictureBox.Image = Image.FromStream(ms)

assuming imagedate field a blobfield.

假设 imagedate 字段是一个blob字段。