English 中文(简体)
VB.net - 插入/检索从我sql数据库直接到/从照片箱的图像
原标题:VB.net - insert/retrieve picture from mysql Database directly to/from a Picturebox

我有了一个时间的黑板,可以找到一部能够做到这一点的法典。 我只想到的是,通过使用该法典把照片储存成一种lob(也许不正确)。

Dim filename As String = txtName.Text + ".jpg"
Dim FileSize As UInt32
Dim ImageStream As System.IO.MemoryStream

ImageStream = New System.IO.MemoryStream
PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg)
ReDim rawdata(CInt(ImageStream.Length - 1))
ImageStream.Position = 0
ImageStream.Read(rawdata, 0, CInt(ImageStream.Length))
FileSize = ImageStream.Length

Dim query As String = ("insert into actors (actor_pic, filename, filesize) VALUES    (?File, ?FileName, ?FileSize)")
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("?FileName", filename)
cmd.Parameters.AddWithValue("?FileSize", FileSize)
cmd.Parameters.AddWithValue("?File", rawData)

cmd.ExecuteNonQuery()

MessageBox.Show("File Inserted into database successfully!", _
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)

但是,在使用以下代码检索图像箱时:

Private Sub GetPicture()
     This retrieves the pictures from a mysql DB and buffers the rawdata into a memorystream 

    Dim FileSize As UInt32
    Dim rawData() As Byte
    Dim conn As New MySqlConnection(connStr)

    conn.Open()
    conn.ChangeDatabase("psdb")

    Dim cmd As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", conn)
    Cmd.Parameters.AddWithValue("?autoid", Actor1Box.Text)

    Reader = cmd.ExecuteReader
    Reader.Read()

     data is in memory 

    FileSize = Reader.GetUInt32(Reader.GetOrdinal("filesize"))
    rawData = New Byte(FileSize) {}

     get the bytes and filesize 
    Reader.GetBytes(Reader.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize)

    Dim ad As New System.IO.MemoryStream(100000)
      Dim bm As New Bitmap

    ad.Write(rawData, 0, FileSize)

    Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below)
    Actor1Pic.Image = im

    Reader.Close()
    conn.Close()
    conn.Dispose()
    ad.Dispose()

我在所述地区发现错误“参数无效”。 FYI 如果任何人甚至拥有比我能够pl倒和bu弄这些同样伟大的东西的更好的(工作)密码例子。

最佳回答

这个问题得不到帮助,无法最终工作。 这里是我的工作守则。

SAVE TO MySQL out of Picturebox (pbPicture)

    Dim filename As String = txtName.Text + ".jpg"
    Dim FileSize As UInt32

    conn.Close()

    Dim mstream As New System.IO.MemoryStream()
    PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
    Dim arrImage() As Byte = mstream.GetBuffer()

    FileSize = mstream.Length
    Dim sqlcmd As New MySqlCommand
    Dim sql As String
    mstream.Close()

    sql = "insert into [your table]  (picture, filename, filesize) 
                               VALUES(@File, @FileName, @FileSize)"

    Try
        conn.Open()
        With sqlcmd
            .CommandText = sql
            .Connection = conn
            .Parameters.AddWithValue("@FileName", filename)
            .Parameters.AddWithValue("@FileSize", FileSize)
            .Parameters.AddWithValue("@File", arrImage)

            .ExecuteNonQuery()
        End With
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        conn.Close()
    End Try

LOAD from MySQL db Back to 电影箱

   Dim adapter As New MySqlDataAdapter
    adapter.SelectCommand = Cmd

    data = New DataTable

    adapter = New MySqlDataAdapter("select picture from [yourtable]", conn)

NOTE! 仅能一度把照片带上图片,这种问话只能给你一个记录。

    commandbuild = New MySqlCommandBuilder(adapter)
    adapter.Fill(data)

    Dim lb() As Byte = data.Rows(0).Item("picture")
    Dim lstr As New System.IO.MemoryStream(lb)
    PbPicture.Image = Image.FromStream(lstr)
    PbPicture.SizeMode = PictureBoxSizeMode.StretchImage
    lstr.Close()
问题回答

水井 当图像时,你正试图投上记忆。 来自Stream的预计系统。 IO。 精简

I just wrote this code as part of my contribution to this forum though not a member but love to help. This code search for multiple records and their corresponding images as you keep searching for record instead of search for one record and close the app to search again. This code allows you to search a record, clear the fields enter the search criteria and search again & again.

    If TextBox3.Text = "" Then   This is the search field to be used it could be any field from your database that will match the value from the database. Either firstname, phone or email etc
        MsgBox("Nothing to search for from the database", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "Oop!")
    End If
    Try
        conn.Open()
        Dim data As New MySqlDataAdapter("SELECT * FROM users_data WHERE phoneno =  " & TextBox3.Text & "  ", conn)

        Dim dTable As New DataTable
        data.Fill(dTable)

        If dTable.Rows.Count > 0 Then
            TextBox1.Text = dTable.Rows(0).Item("firstname")
            TextBox2.Text = dTable.Rows(0).Item("lastname")

             Fetching the corresponding image to this member
            Dim arrImage As Byte()
            Dim myMS As New IO.MemoryStream
            If Not IsDBNull(dTable.Rows(0).Item("myimage")) Then
                arrImage = dTable.Rows(0).Item("myimage")
                For Each ar As Byte In arrImage
                    myMS.WriteByte(ar)
                Next
                PictureBox1.Image = System.Drawing.Image.FromStream(myMS)
            End If

        Else
            MsgBox("No record found for this Phone No: " & TextBox3.Text & " Enter a valid Phone No or consult the Admin Manager", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Record not found")
            clear()
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    Finally
        conn.Close()
    End Try

This code could work for MYSQL Server database and Microsoft SQL databases as well. The only difference is is changing this statement Dim data As New MySqlDataAdapter which is for MYSQL Server to Dim data As New SqlDataAdapter for Microsoft SQL server. Good evening all StackOverflowers

VB.NET - insert/retrieve picture from MySQL Database directly to/from a Picturebox

Example Procedure VISUAL BASIC. NET 2017: I m sharing: 1° Configuration of the table MySQL and variables. 2° Visual design 3° code.

Overview of the procedure: The user put an imagen in a picturebox. The imagen located in picturebox is SAVED in MySQL table. Another option is give the ID of the image (textbox1.text) and then LOAD the image from the MySQL table. There is another button to clear the picturebox but is not strictly necessary. It is not the perfect procedure it has being made only to understand the flow of images load/save to MySQL table AND I SHARE my knoledge with you.

  1. Configure the table in MySQL server. Example: table used: "imagenes" variables:

“idimagen”作为INT。 (主要)

“利马根”作为LONGBLOB(低端)——------>>>>

Mysql table configuration example:
Mysql table configuration example

  1. DESIGN IN VB.NET

Designed form used:
Designed form used

  1. Code used:

Add reference: MySQL.data 6.10.5.0 You need to import: MySql.Data.MySqlClient AND Imports System.IO

Public Class Form1



 Dim Server As String = "XX.XX.XXX.XXX"
    Dim UserID As String = "XXXXXXXXXXXXXX"
    Dim Password As String = "PASSWORD"
    Dim Database As String = "DATABASE NAME"
    Dim Port As Integer = 3306
    Dim AllowUserVariables As Boolean = True

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim ULTIMOID As Integer = 0
        Try
            Dim xxxxcon As New MySqlConnectionStringBuilder()
            xxxxcon.Database = Database
            xxxxcon.Server = Server
            xxxxcon.UserID = UserID
            xxxxcon.Password = Password
            xxxxcon.Port = 3306
            xxxxcon.AllowUserVariables = True
            Dim con As New MySqlConnection(xxxxcon.ToString)
            Dim dbsql As String = "SELECT MAX(idimagen) AS  ULTIMOID  FROM imagenes;"
            Dim cmdMy As New MySqlCommand(dbsql, con)
            con.Open()
            cmdMy.ExecuteNonQuery()
            Try
                ULTIMOID = Convert.ToInt32(cmdMy.ExecuteScalar())
            Catch ex As Exception
                ULTIMOID = 0
            End Try
            con.Close()
        Catch ex As Exception
            MsgBox("Problemas leyendo la BASE para obtener el último ID. Error: " & ex.Message)
        End Try
               Try
            Dim xxxxcon As New MySqlConnectionStringBuilder()
            xxxxcon.Database = Database
            xxxxcon.Server = Server
            xxxxcon.UserID = UserID
            xxxxcon.Password = Password
            xxxxcon.Port = 3306
            xxxxcon.AllowUserVariables = True
            Dim FileSize As UInt32
            Dim con As New MySqlConnection(xxxxcon.ToString)
            Dim mstream As New System.IO.MemoryStream()
            PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
            Dim arrImage() As Byte = mstream.GetBuffer()
            FileSize = mstream.Length
            Dim sqlcmd As New MySqlCommand
            Dim sql As String
            mstream.Close()
            sql = "insert into imagenes (idimagen, imagen) VALUES(@id, @imagen)"
            Try
                con.Open()
                With sqlcmd
                    .CommandText = sql
                    .Connection = con
                    .Parameters.AddWithValue("@id", ULTIMOID + 1)
                    .Parameters.AddWithValue("@imagen", arrImage)
                    .ExecuteNonQuery()
                End With
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally
                con.Close()
            End Try

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        OpenFileDialog2.Filter = "image file (*.jpg, *.bmp, *.png) | *.jpg; *.bmp; *.png| all files (*.*) | *.* "
        If OpenFileDialog2.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            PictureBox1.Image = Image.FromFile(OpenFileDialog2.FileName)
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        PictureBox1.Image = Nothing
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim xxxxcon As New MySqlConnectionStringBuilder()
        xxxxcon.Database = Database
        xxxxcon.Server = Server
        xxxxcon.UserID = UserID
        xxxxcon.Password = Password
        xxxxcon.Port = 3306
        xxxxcon.AllowUserVariables = True

        Dim con As New MySqlConnection(xxxxcon.ToString)
        Try
            Dim ds As New DataSet

            Dim dbsql As String = "SELECT * FROM imagenes WHERE idimagen = " & TextBox1.Text & ";"

            Dim cmdMy As New MySqlCommand(dbsql, con)
            con.Open()
            Dim da As New MySqlDataAdapter(dbsql, con)
            da.Fill(ds, "Imagenes")
            con.Close()
            If ds.Tables("imagenes").Rows.Count > 0 Then
                Dim bytes As [Byte]() = ds.Tables("imagenes").Rows(0).Item(1)
                Dim ms As New MemoryStream(bytes)
                PictureBox1.Image = Image.FromStream(ms)
            Else
                MsgBox("No record found for this Phone No: " & TextBox1.Text)

            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
    End Sub
End Class

如果你改变这种状况,会发生什么情况:

Dim ad As New System.IO.MemoryStream(100000)

:

Dim ad As New System.IO.MemoryStream()

http://www.ohchr.org。

VB array sizes are different than other programming languages, I think you need to do a minus 1:

rawData = New Byte(FileSize - 1) {}

<EDIT 2

坦率地说,请看你掌握的原始二元数据。 所有联合项目都应从FFD8开始,最后采用FFD9。 在你建立<代码>Drawata阵列后插入如下内容: 如果它犯了一个错误,那么你的联合调查小组的信息就会腐败。

    If (rawData(0) = &HFF) AndAlso (rawData(1) = &HD8) Then
        Trace.WriteLine("File start OK")
    Else
        Throw New ApplicationException("Invalid jpg header")
    End If

    If (rawData(rawData.Length - 2) = &HFF) AndAlso (rawData(rawData.Length - 1) = &HD9) Then
        Trace.WriteLine("File end OK")
    Else
        Throw New ApplicationException("Invalid jpg footer")
    End If

EDIT 3

We re going to need to see what the first few bytes of the data look like. Run this and post what gets outputed:

    For I = 0 To 20
        Trace.Write(Convert.ToString(rawData(I), 16).ToUpperInvariant())
    Next




相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签