[英]How to retrieve image fields civilimage1,civilimage2 from SQL Server database to show using image control in ASP.NET with vb.net or c#?
[英]ASP.NET C# Get retrieve and show image from SQL Server database
我想從SQL Server數據庫中檢索圖像並顯示在Image
工具中。
我有這個代碼
<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
}
但是我不能這樣做:
Image1.ImageUrl = ms.FromStream(ms);
因為我得到一個錯誤。
有人可以幫我嗎? 我唯一的問題是顯示圖像。
請幫忙,謝謝。
您可以從字節數組中生成base64string
並將其用作嵌入式圖像源。
byte[] imagem = (byte[])(reader[1]); string base64String = Convert.ToBase64String(imagem) ;
Image1.ImageUrl = String.Format("data:image/jpg;base64,{0}",base64String);
假設:圖片另存為jpg
。
如果不同,則在步驟2中更改行。
免責聲明: Base64string
作為image適用於較小尺寸的圖像,但是如果我們具有較大的圖像,則生成的字符串將具有較大尺寸的字符串。 優點是,瀏覽器不必為每個圖像請求多次(如果您將其實現為image.src= "http://handler-to-image"
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.