图片上传到数据库与显示(转载,C#→VB)

Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.IO
Imports System.Data.SqlClient
Namespace WindowsApplication1
 Public Partial Class Form1
  Inherits Form
  Public Sub New()
   InitializeComponent()
  End Sub
  '选择按钮事件处理 
  Private Sub button1_Click(sender As Object, e As EventArgs)
   openFileDialog1.InitialDirectory = "C:\"
   openFileDialog1.Filter = "图片文件 (*.jpg)|*.jpg"
   openFileDialog1.FilterIndex = 1
   openFileDialog1.RestoreDirectory = True
   openFileDialog1.Multiselect = True
   If openFileDialog1.ShowDialog() = DialogResult.OK Then
    textBox1.Text = openFileDialog1.FileName
   End If
  End Sub
  '上传按钮事件处理 
  Private Sub button2_Click(sender As Object, e As EventArgs)
   Save(PhotoToArray(textBox1.Text.ToString()))
  End Sub
  '将图片信息转换成二进制信息
  Private Function PhotoToArray(path As String) As Byte()
   Dim stream As New FileStream(path, FileMode.Open, FileAccess.Read)
   Dim bufferPhoto As Byte() = New Byte(stream.Length - 1) {}
   stream.Read(bufferPhoto, 0, Convert.ToInt32(stream.Length))
   stream.Flush()
   stream.Close()
   Return bufferPhoto
  End Function
  '把二进制的图片插到数据库
  Private Sub Save(image As Byte())
   Dim sql As String = "insert into Photo(photo_Info) values(@photo)"
   Dim param As New SqlParameter()
   param = New SqlParameter("@photo", SqlDbType.Image)
   param.Value = image
   Dim commd As New SqlCommand(sql, DBhelper.con)
   commd.Parameters.Add(param)
   Try
    DBhelper.con.Open()
    commd.ExecuteNonQuery()
    MessageBox.Show("您已经把图片成功的插入数据库!")
   Catch ex As Exception
    MessageBox.Show(ex.Message)
   Finally
    DBhelper.con.Close()
   End Try
  End Sub
  '显示图片按钮事件处理 
  Private Sub button3_Click(sender As Object, e As EventArgs)
   Dim strSQL As String = "Select   [photo_Info]   From   [Photo]   Where   [photo_Id]=(@photo)"
   Dim param As New SqlParameter()
   param = New SqlParameter("@photo", SqlDbType.Int)
   param.Value = comboBox1.Text.ToString()
   Dim cmd As New SqlCommand(strSQL, DBhelper.con)
   cmd.Parameters.Add(param)
   DBhelper.con.Open()
   Dim reader As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader()
   Try
    reader.Read()
    Dim ms As New MemoryStream(DirectCast(reader("photo_Info"), Byte()))
    Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(ms, True)
    Me.pictureBox1.Image = image
   Catch ex As Exception
    MessageBox.Show(ex.Message)
   Finally
    DBhelper.con.Close()
   End Try
  End Sub
  Private Sub Form1_Load(sender As Object, e As EventArgs)
   ' TODO: 这行代码将数据加载到表“myPhotoDataSet.Photo”中。您可以根据需要移动或移除它。 
   Me.photoTableAdapter.Fill(Me.myPhotoDataSet.Photo)
  End Sub
 End Class
End Namespace

原文地址:https://www.cnblogs.com/shuiguang/p/2071954.html