Almacenar Imagen a MySql.

Estoy desarrollando sistema de gestión de empleados, tengo un formulario de altas, bajas y ediciones. En este formulario quiero agregar, eliminar o modificar la foto del empleado según sea el caso para esto agregue un PictureBox y un botón agregar foto y un procedimiento para convertir la imagen a binario y almacenarla en la tabla MySql. Pero estoy haciendo algo mal ya que no me reconoce una linea de código y no me guarda la image en la tabla.

Te muestro el código que tengo:

Private Function Imagen_Bytes(ByVal Imagen As Image) As Byte()'si hay imagenIf Not Imagen Is Nothing Then'variable de datos binarios en stream(flujo)Dim Bin As New MemoryStream'convertir a bytesImagen.Save(Bin, Imaging.ImageFormat.Jpeg)'retorna binarioReturn Bin.GetBufferElseReturn NothingEnd IfEnd Function'convertir binario a imagenPrivate Function Bytes_Imagen(ByVal Imagen As Byte()) As ImageTry'si hay imagenIf Not Imagen Is Nothing Then'caturar array con memorystream hacia BinDim Bin As New MemoryStream(Imagen)'con el método FroStream de Image obtenemos imagenDim Resultado As Image = Image.FromStream(Bin)'y la retornamosReturn ResultadoElseReturn NothingEnd IfCatch ex As ExceptionReturn NothingEnd TryEnd FunctionPrivate Sub CmdAgregarP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdAgregarP.Click'Dim OPD As OpenFileDialogDim Ruta As StringOFD.ShowDialog()'OFD.ShowDialog()'MessageBox.Show(NOMBRE)Ruta = OFD.FileName.ToString()'MessageBox.Show(RUTA)Me.PBImage.ImageLocation = RutaImagen_Bytes(Me.PBImage.Image)End Sub

Este es el codigo para guardar los datos

Sub Guardar()If String.IsNullOrEmpty(TxtNoGafete.Text) ThenMsgBox("El campo 'Empleado' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtNoGafete.BackColor = Color.YellowTxtNoGafete.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtNombre.Text) ThenMsgBox("El campo 'Nombre' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtNombre.BackColor = Color.YellowTxtNombre.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtRuta.Text) ThenMsgBox("El campo 'Ruta' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtRuta.BackColor = Color.YellowTxtRuta.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtTurno.Text) ThenMsgBox("El campo 'Turno' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtTurno.BackColor = Color.YellowTxtTurno.Focus()Exit SubEnd IfEnd IfEnd IfEnd IfIf conexion.State() = ConnectionState.Closed Thenconexion.Open()End If'compruebo que esten llenas las cajas de textosql = "SELECT * FROM asignacion_de_rutas"SqlB.Connection = conexionSqlB.CommandText = sql'procedo a pasar los datos de los textbox a la variable para guardarSqlB.Parameters.Clear()SqlB.Parameters.AddWithValue("?NoGafete", Me.TxtNoGafete.Text)SqlB.Parameters.AddWithValue("?nombre", Me.TxtNombre.Text)SqlB.Parameters.AddWithValue("?ruta", Me.TxtRuta.Text)SqlB.Parameters.AddWithValue("?turno", Me.TxtTurno.Text)'Img = Imagen_Bytes(PBImage.Image) SqlB.Parameters.AddWithValue("?foto", Img) SqlB.CommandText = "insert into asignacion_de_rutas values(0,?NoGafete,?nombre,?ruta,?turno?,?Foto)"TrySqlB.ExecuteNonQuery()Limpiar()MsgBox("Los datos del 'Empleado' se han guardado Correctamente..........! ", MsgBoxStyle.Information, "NOTIFICACIÓN")Catch ex As ExceptionMsgBox("No es posible Guardar, Verifique! " & ex.Message, MsgBoxStyle.Critical, "ERROR")End Tryconexion.Close()End Sub

Esta es la linea que no me reconoce:

Img = Imagen_Bytes(PBImage.Image)

1 respuesta

Respuesta
1

Aunque no he podido ver bien el código, porque esta todo seguido y es difícil leerlo, supongo que el error es porque no estas enviando el valor correcto en el parámetro a mysql

Tampoco me dices cual es el mensaje del error, solo que en ese linea tienes error.

Hola.

Disculpa corrijo para que se vea bien el código.

Con este código convierto la imagen a binario:

'convertir imagen a binarioPrivate Function Imagen_Bytes(ByVal Imagen As Image) As Byte()'si hay imagenIf Not Imagen Is Nothing Then'variable de datos binarios en stream(flujo)Dim Bin As New MemoryStream'convertir a bytesImagen.Save(Bin, Imaging.ImageFormat.Jpeg)'retorna binarioReturn Bin.GetBufferElseReturn NothingEnd IfEnd Function

Con este otro código convierto de binario a imagen para mostrar la foto en el PictureBox:

'convertir binario a imagenPrivate Function Bytes_Imagen(ByVal Imagen As Byte()) As ImageTry'si hay imagenIf Not Imagen Is Nothing Then'caturar array con memorystream hacia BinDim Bin As New MemoryStream(Imagen)'con el método FroStream de Image obtenemos imagenDim Resultado As Image = Image.FromStream(Bin)'y la retornamosReturn ResultadoElseReturn NothingEnd IfCatch ex As ExceptionReturn NothingEnd TryEnd Function

Con este otro código selecciona la imagen del empleado:

Private Sub CmdAgregarP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdAgregarP.Click'Dim OPD As OpenFileDialogDim Ruta As StringOFD.ShowDialog()'OFD.ShowDialog()'MessageBox.Show(NOMBRE)Ruta = OFD.FileName.ToString()'MessageBox.Show(RUTA)Me.PBImage.ImageLocation = RutaImagen_Bytes(Me.PBImage.Image)End Sub

Con este procedimiento guardo los datos del empleado:

Sub Guardar()If String.IsNullOrEmpty(TxtNoGafete.Text) ThenMsgBox("El campo 'Empleado' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtNoGafete.BackColor = Color.YellowTxtNoGafete.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtNombre.Text) ThenMsgBox("El campo 'Nombre' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtNombre.BackColor = Color.YellowTxtNombre.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtRuta.Text) ThenMsgBox("El campo 'Ruta' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtRuta.BackColor = Color.YellowTxtRuta.Focus()Exit SubElseIf String.IsNullOrEmpty(TxtTurno.Text) ThenMsgBox("El campo 'Turno' no puede ser vacio..........!", MsgBoxStyle.Exclamation, "ATENCIÓN")TxtTurno.BackColor = Color.YellowTxtTurno.Focus()Exit SubEnd IfEnd IfEnd IfEnd IfIf conexion.State() = ConnectionState.Closed Thenconexion.Open()End If'compruebo que esten llenas las cajas de textosql = "SELECT * FROM asignacion_de_rutas"SqlB.Connection = conexionSqlB.CommandText = sql'procedo a pasar los datos de los textbox a la variable para guardarSqlB.Parameters.Clear()SqlB.Parameters.AddWithValue("?NoGafete", Me.TxtNoGafete.Text)SqlB.Parameters.AddWithValue("?nombre", Me.TxtNombre.Text)SqlB.Parameters.AddWithValue("?ruta", Me.TxtRuta.Text)SqlB.Parameters.AddWithValue("?turno", Me.TxtTurno.Text)'Img = Imagen_Bytes(PBImage.Image)SqlB.Parameters.AddWithValue("?foto", Img) SqlB.CommandText = "insert into asignacion_de_rutas values(0,?NoGafete,?nombre,?ruta,?turno?,?Foto)"TrySqlB.ExecuteNonQuery()Limpiar()MsgBox("Los datos del 'Empleado' se han guardado Correctamente..........! ", MsgBoxStyle.Information, "NOTIFICACIÓN")Catch ex As ExceptionMsgBox("No es posible Guardar, Verifique! " & ex.Message, MsgBoxStyle.Critical, "ERROR")End Tryconexion.Close()End Sub

Y esta es la linea que no me reconoce del procedimiento Guardar:

'Img = Imagen_Bytes(PBImage.Image)

Y el error que me muestra es:

Fatal error encontured during command execution.

Espero me puedas ayudar.

Gracias.

1. Esa linea que pones esta comentada, entonces no debería darte error,

2. ¿Si no esta comentada en el código que estas usando de que tipo esta defina esa variable?

3. ¿La columna en Mysql como la tienes definida?

De todas formas, aquí hay un ejemplo de como hacerlo: http://www.e-coffeetech.com/item/36-articulos/desarrollo-de-software/item/96-guardar-imagenes-en-mysql-usando-vbnet.html

Hola.

Aquí tengo comentada la linea:

Dim Resultado As Image = Image.FromStream(Bin)

Y el campo foto lo tengo como Longblob.

Image. FromStream(Bin) directamente a la sentencia en donde tu vas a insertar el registro en la tabla.

No entiendo lo que me quieres decir , creo te faltaron comentarios........?

¿Cuál es el código que usas para insertar la imagen en la base de datos?

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas