Ver Mensaje Individual
  #2 (permalink)  
Antiguo 01/04/2012, 21:02
Avatar de ramirezmario7
ramirezmario7
 
Fecha de Ingreso: febrero-2008
Ubicación: Medellín
Mensajes: 336
Antigüedad: 16 años, 3 meses
Puntos: 56
Respuesta: guardar imagen en sQL desde c#

Hola.
Mira esto a ver si te seirve.

Código:

        /// El método Image2Bytes recibe como parámetro un objeto de tipo Image,
        /// crea un fichero temporal y lo guarda como PNG,
        /// lee el contenido de ese fichero y lo asigna a un array de tipo Byte,
        /// para finalmente devolver dicho array.
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        private byte[] Image2Bytes(Image img)
        {
            string sTemp = Path.GetTempFileName();
            FileStream fs = new FileStream(sTemp, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            img.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
            fs.Position = 0;

            int imgLength = Convert.ToInt32(fs.Length);
            byte[] bytes = new byte[imgLength];
            fs.Read(bytes, 0, imgLength);
            fs.Close();
            return bytes;
        }

/// <summary>
        /// el método Byte2Image recibe un array de bytes como parámetro,
        /// lo asigna a un objeto del tipo MemoryStream y ese "stream" lo utiliza para crear un objeto del tipo Bitmap,
        /// finalmente devuelve ese objeto que en el fondo es un objeto de tipo Image.
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private Image Bytes2Image(byte[] bytes)
        {
            if (bytes == null) return null;

            MemoryStream ms = new MemoryStream(bytes);
            Bitmap bm = null;
            
            try
            {
                bm = new Bitmap(ms);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return bm;
        }


#region guardar imagen

            byte[] img = Image2Bytes(this.pbImg.Image);


            string sql = "insert into tbl_imagenes values(@img)";
            string cadena = @"Data Source=DESARROLLO\SQLEXPRESS;Initial Catalog=bdimagenes;Integrated Security=True";
            SqlConnection conexion = new SqlConnection(cadena);
            SqlCommand comando = new SqlCommand(sql, conexion);

            try
            {
                conexion.Open();
                comando.Parameters.AddWithValue("@img", img);

                comando.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conexion.Close();
            }

            #endregion


#region Consultar imagen

            string sql = "select top 1 foto from tbl_imagenes";
            string cadena = @"Data Source=DESARROLLO\SQLEXPRESS;Initial Catalog=bdimagenes;Integrated Security=True";
            SqlConnection conexion = new SqlConnection(cadena);
            SqlCommand comando = new SqlCommand(sql, conexion);
            

            try
            {
                SqlDataReader dr;
                conexion.Open();
                dr =  comando.ExecuteReader();

                dr.Read();
                
                byte[] img = (byte[])dr[0];

                this.pbcarga.Image = Bytes2Image(img);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conexion.Close();
            }

            #endregion
Ese codigo de convertir la imagen lo encontre hace mucho tiempo pero la verdad es que no me acuerdo de donde lo saque.

En el ejemplo que hice guardo la imagen de un picturebox a la base de datos y tambien la cargo a otro picturepox desde la base de datos
__________________
Mario Ramírez
Desarrollador .NET MCTS
https://www.mcpvirtualbusinesscard.c...nteractivecard

Última edición por ramirezmario7; 01/04/2012 a las 21:09