【问题标题】:ASP.NET C# Get retrieve and show image from SQL Server databaseASP.NET C# 从 SQL Server 数据库中获取并显示图像
【发布时间】:2014-10-21 19:15:41
【问题描述】:

我想从 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);

因为我得到一个错误。

有人可以帮助我吗?我唯一的问题是显示图像。

请帮忙,谢谢。

【问题讨论】:

  • 推荐的方式是存储图片的路径,这样一旦从数据库中检索到,就可以构建图片的url
  • 你应该将readerMemoryStreamcmdconnection 包装在using 块中。
  • 没有办法回答这个问题,因为你没有展示 Image1 是如何声明的。这是一个网络应用程序吗?如果是这样,那么您将需要一个网址。当访问该 URL 时,您可能还需要一个服务器来传递数据库中的数据。或者您可以将图像存储为文件并使用不需要服务的标准 url。
  • ...或者编写一个 ashx 处理程序从数据库中获取图像并将其作为二进制流返回。
  • 我很确定保存图片的路径不是一个好主意,但没关系:)

标签: c# asp.net sql-server


【解决方案1】:

您可以从字节数组中生成base64string 并将其用作内联图像源。

  1. 转换为 base64 字符串。 Refer this.
byte[] imagem = (byte[])(reader[1]);
string base64String = Convert.ToBase64String(imagem) ;
  1. 将此字符串用作内联图像,如下所示。 Refer this

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

假设:图片保存为jpg

如果这不同,则在步骤#2 中更改行。

免责声明: Base64string 因为图像适合小尺寸的图像,但如果我们有更大的图像,那么生成的字符串将具有大尺寸的字符串。优点是,浏览器不必为每个图像多次请求(如果您将其实现为image.src= "http://handler-to-image")。

【讨论】:

  • 当然,这只是图片下载大小的两倍。
  • 这个解决方案揭示了一个可怕的设计。这不会扩展。
猜你喜欢
  • 2018-11-06
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-19
  • 2017-08-03
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多