界面如下:
Dim L_Err As String = "" Dim opd As OpenFileDialog = New OpenFileDialog() opd.CheckFileExists = True opd.CheckPathExists = True opd.RestoreDirectory = True opd.DefaultExt = "*.*" opd.Filter = "图像文件 (*.bmp;*.gif;*.jpg;*.jpeg;*.png)|*.bmp;*.gif;*.jpg;*.jpeg;*.png" opd.ShowDialog() If opd.FileName <> "" Then Me.PicBox.Image = Image.FromFile(opd.FileName) Me.PicBox.ImageLocation = opd.FileName End If2、确定按钮代码
If ToStr(Me.PicBox.ImageLocation).Trim() <> "" Then Try Dim ssql1 As String = "" 'ssql1 = "insert into U_CallInfoSet(backImage) values(@fs)" //插入或者更新语句 ssql1 = "update U_CallInfoSet set backImage=@fs" sqlHelper.ExecutesqlWithImg(ssql1,My.Computer.FileSystem.ReadAllBytes(Me.PicBox.ImageLocation)) Catch ex As Exception MessageBox.Show(ex.ToString()) End Try End If
3、界面加载事件显示
'取得数据库字段 dt.Rows(0)("Pic")
If dt.Rows(0)("Pic") Is DBNull.Value Then Me.PicBox.Image = Nothing Else Me.PicBox.Image = GetImage(dt.Rows(0)("Pic")) End If4、需要用到的方法
''' <summary> ''' 字节数组转换为Image类型 ''' </summary> ''' <param name="bData"></param> ''' <returns></returns> ''' <remarks></remarks> Public Function GetImage(ByVal bData As Byte()) As Image Try Using fStream As Stream = New MemoryStream(bData.Length) Dim bWriter As New BinaryWriter(fStream) bWriter.Write(DirectCast(bData,Byte())) bWriter.Flush() Dim bitMap As New System.Drawing.Bitmap(fStream) bWriter.Close() fStream.Close() Dim iImage As Image = System.Drawing.Image.FromHbitmap(bitMap.GetHbitmap()) Return iImage End Using Catch e As System.IO.IOException Throw New Exception(e.Message & "Read image data error!") End Try End Function ''' <summary> ''' 处理sql中操作Image类型 ''' </summary> ''' <param name="strsql">sql语句</param> ''' <param name="fs">图像字节,数据库的字段类型为image的情况</param> ''' <returns>影响的记录数</returns> Public Shared Function ExecutesqlWithImg(ByVal strsql As String,ByVal fs As Byte()) As Integer Dim strCon As String = "Data Source=xxx;Initial Catalog=temp;User ID=sa;Password=123" Using connection As New sqlConnection(strCon) Dim cmd As New sqlCommand(strsql,connection) Dim myParameter As New System.Data.sqlClient.sqlParameter("@fs",sqlDbType.Image) myParameter.Value = fs cmd.Parameters.Add(myParameter) Try connection.Open() Dim rows As Integer = cmd.ExecuteNonQuery() Return rows Catch e As System.Data.sqlClient.sqlException Throw e Finally cmd.Dispose() connection.Close() End Try End Using End FunctionOK! 原文链接:https://www.f2er.com/vb/257801.html