ASP.NET C#获取检索和SQL Server数据库显示图片 [英] ASP.NET C# Get retrieve and show image from SQL Server database
问题描述
我要检索从SQL Server数据库并显示在图像的图像
工具。
我有这样的code
< ASP:图片ID =Image1的=服务器的CssClass =蓝紫魅力HEIGHT =166pxWIDTH =488px/>
SqlConnection的连接= NULL;字符串连接字符串=数据源= \\\\ SQLEX $ P $干燥综合征;初始目录=睾丸;集成安全性= TRUE;池=假;
连接=新的SqlConnection(连接字符串);
connect.Open();字符串SCMD =SELECT标识,IMAGEM其中id = 2;
CMD的SqlCommand =新的SqlCommand(SCMD,连接);SqlDataReader的读者= cmd.ExecuteReader();reader.Read();如果(reader.HasRows)
{
Label1.Text =读者[0]的ToString();
字节[] = IMAGEM(字节[])(阅读器[1]); MemoryStream的毫秒=新的MemoryStream(IMAGEM); Image1.ImageUrl = ms.FromStream(毫秒); //我想这
}
但我不能做到这一点:
Image1.ImageUrl = ms.FromStream(毫秒);
,因为我得到一个错误。
有人请帮助我?我唯一的问题是显示图像。
请帮忙,谢谢。
您可以生成 base64string
出字节数组,并用其作为内嵌图像源。
- 转换为base64string。 转寄此。
字节[] = IMAGEM(字节[])(阅读器[1]);
字符串base64String = Convert.ToBase64String(IMAGEM);
块引用><醇开始=2>使用此字符串像下面的嵌入式图像。 转寄此。
Image1.ImageUrl =的String.Format(数据:图像/ JPG; BASE64,{0},base64String);
假设:保存为
。JPG
图片如果此不同,然后更改行第2步。
声明:
Base64string
作为图像,适用于小尺寸图像,但如果我们有更大的影像,然后生成的字符串将有大尺寸串。优点是,浏览器不必要求多次为每个图像(如果你实现了这个为image.src =HTTP://处理到图像的
)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.
解决方案You can generate
base64string
out of byte array and use that as inline image source.
- Convert to base64string. Refer this.
byte[] imagem = (byte[])(reader[1]); string base64String = Convert.ToBase64String(imagem) ;
- 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 asimage.src= "http://handler-to-image"
).这篇关于ASP.NET C#获取检索和SQL Server数据库显示图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!