you are been banned
you are been banned

Reputation: 55

ASP.NET C# Get retrieve and show image from SQL Server database

I want to retrieve an image from a SQL Server database and show in a Image tool.

I have this code

<asp:Image ID="Image1" runat="server" CssClass="style2" Height="166px" Width="488px" />


SqlConnection connect = null;

string connectstring = "Data Source=.\\SQLEXPRESS;Initial Catalog=teste;Integrated Security=true;pooling=false";
connect = new SqlConnection(connectstring);
connect.Open();

string Scmd = "SELECT id, imagem where id = 2";
SqlCommand cmd = new SqlCommand(Scmd, connect);

SqlDataReader reader = cmd.ExecuteReader();

reader.Read();

if (reader.HasRows)
{
    Label1.Text = reader[0].ToString();                        
    byte[] imagem = (byte[])(reader[1]);

    MemoryStream ms = new MemoryStream(imagem);

    Image1.ImageUrl = ms.FromStream(ms); //i tried this
}

But I can't do this:

Image1.ImageUrl = ms.FromStream(ms);

because I get an error.

Somebody please can help me? The only problem I have is show the image.

Please help, thanks.

Upvotes: 0

Views: 16326

Answers (1)

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can generate base64string out of byte array and use that as inline image source.

  1. Convert to base64string. Refer this.
byte[] imagem = (byte[])(reader[1]);
string base64String = Convert.ToBase64String(imagem) ;
  1. Use this string as inline image like following. Refer this.

Image1.ImageUrl = String.Format("data:image/jpg;base64,{0}",base64String);

Assumption: image saved as jpg.

If this differs, then change line in step#2.

Disclaimer: Base64string as image is suitable for small sized image , but if we have bigger image, then the string produced will have large sized string. Advantage is , browser don't have to request multiple times for each image ( if you implemented this as image.src= "http://handler-to-image").

Upvotes: 5

Related Questions