2011-09-12 19 views
10

Tengo datos binarios de una imagen en mi base de datos, y quiero mostrarlos en un control de imagen en ASP.NET. ¿Cómo? Si es imposible, encuentre otra forma de guardarlo en la base de datos y mostrarlo en un control de imagen.Convertir de datos binarios a un control de imagen en ASP.NET

+2

Echa un vistazo a la respuesta a esta pregunta similar: http://stackoverflow.com/questions/6987433/display-image-from-database-in-asp-net-with-c – IrishChieftain

+0

o este: http://stackoverflow.com/q/612342/76051 – Carsten

Respuesta

29

Crear un elemento HTML normal img así:

<img runat="server" id="image" /> 

Y en code behind hacer esto:

image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes); 

Dónde imageBytes es una byte[] .

Ya ha terminado. La imagen se mostrará.

+0

Esta es, de lejos, la forma más sencilla de mostrar imágenes binarias hasta el momento. PERO encontré que este método funciona solo con imágenes jpg. Intenté esto con imágenes png pero no funcionó. – Arbaaz

+0

El método funciona en jpg y png, siempre que el navegador lo admita. Puede ser que su navegador no lo admita o su implementación tenga errores. – Icarus

+0

¿Puede explicar 'data: image/png; base64'? – Arbaaz

1

En un manipulador genérico (.ashx):

public class ImageHandler : IHttpHandler 
     { 

      public void ProcessRequest(HttpContext context) 
      { 

        if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"])){ 
        try 
        { 
         string ImageId = context.Request.QueryString["ImageId"].ToString(); 
         ImageDataModel idm = new ImageDataModel(); 
         byte[] ImageData = idm.getImageData(ImageId); 

         context.Response.ContentType = "image/JPEG"; 
         context.Response.OutputStream.Write(ImageData, 0, ImageData.Length); 


        } 
4

más probable es que la imagen se almacena como una matriz de bytes en la base de datos. Si es así, entonces usted puede utilizar esto:

public static System.Drawing.Image ByteArrayToImage(byte[] bArray) 
{ 
    if (bArray == null) 
     return null; 

    System.Drawing.Image newImage; 

    try 
    { 
     using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length)) 
     { 
      ms.Write(bArray, 0, bArray.Length); 
      newImage = System.Drawing.Image.FromStream(ms, true); 
     } 
    } 
    catch (Exception ex) 
    { 
     newImage = null; 

     //Log an error here 
    } 

    return newImage; 
} 
1
public Byte[] Ret_image(Int32 id) 
{ 
    SqlCommand cmd = new SqlCommand(); 
    cmd.CommandText = "select * from tbimage where [email protected]"; 
    cmd.Connection = con; 
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; 
    SqlDataReader dr = cmd.ExecuteReader(); 
    dr.Read(); 
    Byte[] ar = (Byte[])(dr[1]); 
    dr.Close(); 
    cmd.Dispose(); 
    return ar; 
} 
1
protected void Button2_Click(object sender, EventArgs e) 
{ 
    Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text)); 
    String st = Server.MapPath("abc.jpg"); 
    FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write); 
    fs.Write(ar, 0, ar.Length); 
    fs.Close(); 
    Image1.ImageUrl = "abc.jpg";   
} 

utilizar este evento para el botón de clic para recuperar la imagen y llame al método Ret_Image aquí.

0
SqlConnection con = new SqlConnection(); 
string _path; 
Using SYstem.IO; 
Using System.Data.SQLClient; 

//convert Image to binary and save in DB 

private void button1_Click(object sender, EventArgs e) 
{ 
    if (openFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     _path = openFileDialog1.FileName; 
     InsertInSQL(_path); 
    } 
} 

private void InsertInSQL(string _path) 
{ 
    con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS; 
    string strQ = "insert into dbo.PicTBL(Pic)values(@p)"; 
    SqlCommand command = new SqlCommand(strQ,con); 
    command.Parameters.AddWithValue("@p",ImageToBinary(_path)); 
    con.Open(); 
    command.ExecuteNonQuery(); 
    con.Close(); 
}  

public static byte[] ImageToBinary(string _path) 
{ 
    FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read); 
    byte[] b = new byte[fS.Length]; 
    fS.Read(b, 0, (int)fS.Length); 
    fS.Close(); 
    return b; 
} 

//Convert Binary to imge and save in a folder 
private void button1_Click_1(object sender, EventArgs e) 
{ 
    DataTable dt = Rimage(); 
    foreach (DataRow row in dt.Rows) 
    { 
     byte[] b = (byte[])row["Pic"]; 
     Image img = BinaryToImage(b); 
     img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg"); 
    } 
} 

private Image BinaryToImage(byte[] b) 
{ 
    if (b == null) 
     return null; 

    MemoryStream memStream = new MemoryStream(); 
    memStream.Write(b, 0, b.Length); 

    return Image.FromStream(memStream); 
} 

private DataTable Rimage() 
{ 
    con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS; 
    SqlCommand cmd = new SqlCommand(); 
    cmd.CommandText = "select * from dbo.PicTBL"; 
    cmd.Connection = con; 
    SqlDataAdapter adp = new SqlDataAdapter(cmd); 
    DataTable dt = new DataTable(); 
    con.Open(); 
    adp.Fill(dt); 

    return dt; 
} 
+0

¡Es todo lo que hice! Disfrútala –

Cuestiones relacionadas