2012-05-04 8 views
9

Estoy tratando de cargar imágenes de la base de datos a PictureBox. Utilizo estos siguientes códigos para cargarlos en mi imagen. He escrito un código pero no sé qué debería hacer para continuar.Cargando PictureBox Imagen de la base de datos

Cualquier ayuda será apreciada.

private void button1_Click(object sender, EventArgs e) 
    { 
     sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True"); 
     cmd = new SqlCommand(); 
     cmd.Connection = sql; 
     cmd.CommandText = ("select Image from Entry where EntryID [email protected]"); 
     cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text)); 
    } 

Respuesta

13

continuar con algo como esto en el Button1_Click:

// Your code first, here. 

var da = new SqlDataAdapter(cmd); 
var ds = new DataSet(); 
da.Fill(ds, "Images"); 
int count = ds.Tables["Images"].Rows.Count; 

if (count > 0) 
{ 
    var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"]; 
    var stream = new MemoryStream(data); 
    pictureBox1.Image = Image.FromStream(stream); 
} 
+0

Muchas gracias. funcionó. – aliprogrammer

+0

En mi base de datos marqué como permitir nulos para la columna Imagen. pero cuando utilizo estos códigos, si no hay ninguna imagen en la fila, encontraré un error – aliprogrammer

+0

@aliprogrammer: Es casi la misma respuesta que publiqué en la url anterior (vea la muestra número 7 en la referencia) – GoRoS

2

Suponiendo que tenemos una base de datos simple con una tabla llamada BLOBTest:

CREATE TABLE BLOBTest 
(
BLOBID INT IDENTITY NOT NULL, 
BLOBData IMAGE NOT NULL 
) 

Podríamos recuperar la imagen a codificar de la siguiente manera:

try 
{ 
    SqlConnection cn = new SqlConnection(strCn); 
    cn.Open(); 

    //Retrieve BLOB from database into DataSet. 
    SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn); 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    da.Fill(ds, "BLOBTest"); 
    int c = ds.Tables["BLOBTest"].Rows.Count; 

    if(c>0) 
    { //BLOB is read into Byte array, then used to construct MemoryStream, 
     //then passed to PictureBox. 
     Byte[] byteBLOBData = new Byte[0]; 
     byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]); 
     MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); 
     pictureBox1.Image= Image.FromStream(stmBLOBData); 
    } 
    cn.Close(); 
} 
catch(Exception ex) 
{MessageBox.Show(ex.Message);} 

Este código recupera las filas desde la tabla BLOBTest en la base de datos en un DataSet, copia la imagen añadida más recientemente en una matriz Byte y luego en un objeto MemoryStream, y luego carga el MemoryStream en la propiedad Image del control PictureBox.

guía de referencia completa:

http://support.microsoft.com/kb/317701

+0

Mientras que este enlace puede responder a la pregunta, es mejor incluir las partes esenciales de la respuesta aquí y proporcionan el enlace de referencia. Las respuestas de solo enlace pueden dejar de ser válidas si la página vinculada cambia. –

+0

@ChrisHaas tiene toda la razón, he actualizado la respuesta. – GoRoS

0
private void btnShowImage_Click(object sender, EventArgs e) 
{ 
    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;"; 
    Con = new OleDbConnection(@constr); 
    Con.Open(); 
    Com = new OleDbCommand(); 
    Com.Connection = Con;  
    Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id = " + val + " "; 
    OleDbDataReader reader = Com.ExecuteReader(); 
    if (reader.Read()) 
    { 
     byte[] picbyte = reader["Photo"] as byte[] ?? null; 
     if (picbyte != null) 
     { 
      MemoryStream mstream = new MemoryStream(picbyte); 
      pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream); 
     { 
     System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream); 
    } 
} 
Cuestiones relacionadas