IMAGEM VB.NET E MYSQL

ERLANMG 10/05/2017 16:53:07
#473877
Boa tarde!

Estou precisando salvar e recuperar imagem usando VbNet e Mysql, gostaria da ajuda de voces;

1 - Já criei um campo formato MediumBlob no banco mysql:
2 - No formulário tenho um botão localizar imagem e um picturebox.
Segue código dentro do botão localizar:
Try
Dim ofd1 As New OpenFileDialog()
ofd1.Filter = [Ô]Imagens | *.jpg[Ô]
If ofd1.ShowDialog() = DialogResult.OK Then
nomeArquivoImagem = ofd1.FileName
picFoto.Image = Image.FromFile(ofd1.FileName)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

3 - A questão é a seguinte como faço para salvar a imagem no bd segue o parte do código que uso para salvar no BD:


[ô][ô][ô]para converter a imagem uso

Dim br As BinaryReader
Dim fs As FileStream
Dim NomeArquivoFoto As String = nomeArquivoImagem
Dim DadosImagem() As Byte
fs = New FileStream(NomeArquivoFoto, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
DadosImagem = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()






conn = New MySqlConnection()
conn.ConnectionString = Con_S
SQL = [Ô]insert into veiculos (placa,[Ô]
SQL = SQL + [Ô]numero,[Ô]
SQL = SQL + [Ô]descricao,[Ô]
SQL = SQL + [Ô]cod_tipo_veiculo,[Ô]
SQL = SQL + [Ô]tipo_veiculo,[Ô]
SQL = SQL + [Ô]crlv,[Ô] //// nome do campo mediublob no bd
SQL = SQL + [Ô]ativo) values ([ô][Ô]
SQL = SQL + mtbPlaca.Text + [Ô] [ô],[ô][Ô]
SQL = SQL + txtCodigoFrota.Text + [Ô][ô],[ô][Ô]
SQL = SQL + txtDescricao.Text + [Ô][ô],[ô][Ô]
SQL = SQL + Mid(cmbTipoVeiculo.Text, 1, 3) + [Ô][ô],[ô][Ô]
SQL = SQL + xxxxxxxxxxxxxxxxxxx + [Ô][ô],[ô][Ô] //// aqui que coloco para salvar a imagem
If cmbSituacao.Text = [Ô]ATIVO[Ô] Then
SQL = SQL + [Ô]SIM[Ô] + [Ô][ô])[Ô]
ElseIf cmbSituacao.Text = [Ô]INATIVO[Ô] Then
SQL = SQL + [Ô]NAO[Ô] + [Ô][ô])[Ô]
End If

conn.Open()
cmd = New MySqlCommand(SQL, conn)
Dim retorno As Integer = cmd.ExecuteNonQuery()

Desde já agradeço pela atenção e ajuda.
Abraços,



DS2T 10/05/2017 17:45:04
#473878
Recomendo veementemente usar parâmetros, ao invés de sair concatenando string.
Mas respondendo sua resposta, você pode usar o BitConverter para gerar uma valor válido para envio.

Algo assim:

Private function RetornaStringFromBytes(array as byte())
return string.Format([Ô]0x{0}[Ô], BitConverter.ToString(array).Replace([Ô]-[Ô], [Ô][Ô]))
end function

Abraços!
OMAR2011 10/05/2017 18:32:00
#473879
Mudei agora para Mysql.
Mude para o tipo de imagem a ser gravada,
Estou usando o Blob.
Dim strimg As String
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim opf As New OpenFileDialog
opf.Filter = [Ô]Imagens(*.jpg;*.Png;*.gif)|*.jpg;*.Png;*.gif[Ô]
If opf.ShowDialog = DialogResult.OK Then
Dim img As Bitmap
img = New Bitmap(strimg)
Pic1.Image = img
End If
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Using con As New MySqlConnection([Ô]server=Localhost;user id=root; password=12qw; database=bras2016;convert zero datetime=True[Ô])
[ô]Try
con.Open()

If strimg <> [Ô][Ô] Then
Dim fs As New System.IO.FileStream(strimg, System.IO.FileMode.Open, FileAccess.Read)
Dim picbyte As [Byte]() = New [Byte](fs.Length - 1) {}
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
Dim cmd As New MySqlCommand()
With cmd
[ô]COD,DESCRICAO,DATAFABR,DATAVENC,LABORATORIO,OBS,FOTO,DREGISTRO
cmd.CommandText = [Ô]Insert into testeimg (nome,img)values(?,?)[Ô]
cmd.CommandType = CommandType.Text
[ô]cmd.Parameters.Add([Ô]@Caracteristicas[Ô], OleDbType.VarChar).Value = txtNome.Text
cmd.Parameters.Add(New MySqlParameter([Ô]@Descricao[Ô], MySqlDbType.VarChar)).Value = txtDescricao.Text
cmd.Parameters.Add(New MySqlParameter([Ô]@img[Ô], MySqlDbType.Blob, picbyte.Length)).Value = picbyte
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox([Ô]Registro gravado[Ô], MsgBoxStyle.Information)
End With
End If
End Using
End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Using con As New MySqlConnection([Ô]server=Localhost;user id=root; password=12qw; database=bras2016;convert zero datetime=True[Ô])

Dim cmd As New MySqlCommand()
Dim dr As MySqlDataReader
con.Open()

cmd = con.CreateCommand

With cmd
.CommandType = CommandType.Text
.CommandText = [Ô]select * From Testeimg where id =[ô][Ô] & txtId.Text & [Ô][ô][Ô]
[ô].CommandText = [Ô]select * From testeimg where id=(select min(id) from testeimg where id > ?)[Ô]
.Parameters.Add([Ô]@id[Ô], MySqlDbType.Int16)
.Parameters([Ô]@id[Ô]).Value = txtId.Text
End With

dr = cmd.ExecuteReader(CommandBehavior.SingleRow)
If dr.Read() Then
txtDescricao.Text = [Ô][Ô] & dr(1)
If Pic1.Image IsNot Nothing Then
Pic1.Image.Dispose()
End If
Dim fsimagem As New FileStream([Ô]Image.jpg[Ô], FileMode.Create)
Dim blob As Byte() = DirectCast(dr.Item([Ô]Img[Ô]), Byte())
fsimagem.Write(blob, 0, blob.Length)
fsimagem.Close()
fsimagem = Nothing
Pic1.Image = Image.FromFile([Ô]Image.jpg[Ô])
Pic1.Show()

dr.Close()
End If
con.Close()

End Using

End Sub
DAMASCENO.CESAR 11/05/2017 14:29:45
#473892
[txt-color=#e80000]para Inserir Foto no BD usando update
[/txt-color]

[ô] no form
Imports ImgDataTable [ô]referencia para imagens
[ô]Coloca no form no botao inserir ou atualizar
  Dim IMG As Bitmap
Dim Str As String = [Ô]UPDATE Tabela SET foto = @image WHERE condicao;[Ô]
[ô]==INSERIR FOTO NO BD=============================
If Not (PctFoto.Image Is Nothing) Then
[ô]Dim fileName As String = Path.GetTempFileName()
Dim fileName As String = Path.GetTempPath & [Ô]img1.jpg[Ô]
IMG = PctFoto.Image
File.Delete(fileName)
IMG.Save(fileName)
Dim CAMINHO As String = fileName
Dim myStream As FileStream = New FileStream(CAMINHO, FileMode.Open, FileAccess.Read)
[ô][ô] Create a buffer to hold the stream of bytes
Dim myImageBuffer(myStream.Length) As Byte
Dim myAdapter As CategoriesTableAdapter = New CategoriesTableAdapter()
[ô][ô] Read the bytes from this stream and put it into the image buffer
myStream.Read(myImageBuffer, 0, Convert.ToInt32(myStream.Length))
[ô][ô] Close the stream
myStream.Close()
myAdapter.insertNImage(Str, myImageBuffer)
End If


[ô]classe que faz a inserção (name space)


  #Region [Ô]Using Statements[Ô]

Imports System
Imports System.Collections.Generic
Imports System.Text

Imports System.IO
Imports System.Data
Imports MySql.Data.MySqlClient
#End Region

Namespace ImgDataTable

Partial Public Class CategoriesTableAdapter
Private Connection As String = [Ô]Sua conexão;[Ô]
[ô][ô][ô] <summary>
[ô][ô][ô] The insertNewImage method takes all the information about the image and stores it
[ô][ô][ô] in the database. This method accesses a stored procedure to insert the data and returns
[ô][ô][ô] the success statement or error message.
[ô][ô][ô] </summary>
[ô][ô][ô] <param name=[Ô]CategoryID[Ô]></param>
[ô][ô][ô] <param name=[Ô]photographName[Ô]></param>
[ô][ô][ô] <param name=[Ô]myBuffer[Ô]></param>
[ô][ô][ô] <returns></returns>
[ô][ô][ô]
Public Function insertNewImage(ByVal CategoryID As Integer, ByVal photographName As String, ByRef myBuffer() As Byte) As String
Return [Ô][Ô]
End Function

Public Function insertNImage(ByVal StrSQL As String, ByRef myBuffer() As Byte) As String

Dim message As String = [Ô][Ô]
Dim myConnection As MySqlConnection

myConnection = New MySqlConnection(Connection)

Try
myConnection.Open()

[ô]Dim fsImage As New FileStream([Ô]d:\fotocrim\690.940.jpg[Ô], FileMode.Open)
[ô][ô] Create a stored procedure command
Dim myCommand As New MySqlCommand
[ô]
myCommand = myConnection.CreateCommand
myCommand.CommandText = StrSQL

[ô][ô] Add the image parameter and set myBuffer as the value.
myCommand.Parameters.Add([Ô]@image[Ô], MySqlDbType.Blob).Value = myBuffer

[ô][ô] Execute the insert
myCommand.ExecuteNonQuery()

[ô][ô] Close the Connection
myConnection.Close()

[ô][ô] Assign the success message
message = [Ô]foto inserida![Ô]

Catch ex As Exception
MsgBox(Err.Number & [Ô] - [Ô] & ex.Message)
[ô][ô] Assign the error message
message = Err.Number & [Ô] - [Ô] & ex.Message
End Try
Return message

End Function

[ô][ô][ô] <summary>
[ô][ô][ô] The getCategories method is a general method that returns a DataSet with Category
[ô][ô][ô] information in it.
[ô][ô][ô] </summary>
[ô][ô][ô] <returns></returns>
Public Function getCategories(ByVal MyQuery As String) As DataSet

Dim myConnection As MySqlConnection
Dim myCommand As MySqlCommand

Dim myDataSet As DataSet = New DataSet()
Dim myAdapter As MySqlDataAdapter
myConnection = New MySqlConnection(Connection)
Try
myConnection.Open()
myCommand = New MySqlCommand()
myCommand.CommandText = MyQuery
myCommand.Connection = myConnection
myAdapter = New MySqlDataAdapter(myCommand)
myAdapter.Fill(myDataSet)
myConnection.Close()
Catch ex As Exception
Throw ex
End Try

Return myDataSet
End Function

[ô][ô][ô] <summary>
[ô][ô][ô] The getImages method accesses the database and return Image information
[ô][ô][ô] based on the CategoryID that is passed in.
[ô][ô][ô] </summary>
[ô][ô][ô] param name=[Ô]CategoryID[Ô]/param
[ô][ô][ô] <returns></returns>
[ô][ô][ô]
Public Function getImages(ByVal MyQuery As String) As DataSet
Dim myConnection As MySqlConnection
Dim myCommand As MySqlCommand
Dim myDataSet As DataSet = New DataSet()
Dim myAdapter As MySqlDataAdapter
myConnection = New MySqlConnection(Connection)
Try
myConnection.Open()
myCommand = New MySqlCommand()
myCommand.CommandText = MyQuery
myCommand.Connection = myConnection
myAdapter = New MySqlDataAdapter(myCommand)
myAdapter.Fill(myDataSet)
Catch ex As Exception
Throw ex
End Try
Return myDataSet
End Function
End Class
End Namespace


OBS:
Faça seu login para responder