[英]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. 我想从SQL Server数据库中检索图像并显示在Image
工具中。
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. 请帮忙,谢谢。
You can generate base64string
out of byte array and use that as inline image source. 您可以从字节数组中生成base64string
并将其用作嵌入式图像源。
byte[] imagem = (byte[])(reader[1]); string base64String = Convert.ToBase64String(imagem) ;
Image1.ImageUrl = String.Format("data:image/jpg;base64,{0}",base64String);
Assumption: image saved as jpg
. 假设:图片另存为jpg
。
If this differs, then change line in step#2. 如果不同,则在步骤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. 免责声明: Base64string
作为image适用于较小尺寸的图像,但是如果我们具有较大的图像,则生成的字符串将具有较大尺寸的字符串。 Advantage is , browser don't have to request multiple times for each image ( if you implemented this as image.src= "http://handler-to-image"
). 优点是,浏览器不必为每个图像请求多次(如果您将其实现为image.src= "http://handler-to-image"
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.