簡體   English   中英

如何從SQL Server中讀取圖像?

[英]How Can I Read Image From SQL Server?

我使用MemoryStream將圖像保存在SQL Server中。

現在,我想從SQL Server中讀取所有圖像並將其顯示在<a href="this is eath of images" >

for (i = 0; i <=  dt.Rows.Count ; i++)
{
   Byte[] img = (Byte[])(reader["image"]);
   MemoryStream ms = new MemoryStream(img);
   BinaryWriter imgforshow = new BinaryWriter(ms);
   ms.Write(img, 0, img.Length);
   div1.InnerHtml = div1.InnerHtml + "<a href='"+ imgforshow +"' runat=server data-   lightbox=roadtrip title=''>";
   div1.InnerHtml = div1.InnerHtml + "<img src='"+ imgforshow +"' width=100 height=140></a> ";
}

如何在此行中顯示圖像?

 div1.InnerHtml = div1.InnerHtml + "<a href='"+ imgforshow +"'......
 div1.InnerHtml = div1.InnerHtml + "<img src='"+ imgforshow +"'.......

我建議編寫一個寫回圖像的圖像處理程序。 您可以使用如下形式:

public void ProcessRequest(HttpContext context)
{
    string id = context.Request.QueryString["id"];
    byte[] img = GetImage(id);
    context.Response.ContentType = "image/jpeg"; // change accordingly
    context.Response.BinaryWrite(img);
    context.Response.Flush();
    context.Response.Close();   
}

請注意,根據您的圖片類型,您需要更改響應的內容類型。 GetImage將為具有指定id的圖像返回一個字節數組。 您無需將其傳遞給MemoryStream。

您的SQL查詢如下所示:

從id = @id的圖像中選擇圖像

try
{
    SqlConnection connection = new SqlConnection(connectionString);
    connection.Open();
    SqlCommand command = new SqlCommand(connection);
    command.CommandText = sqlQuery;
    command.Parameters.Add("id", id);
    command.ExecuteNonQuery();
    connection.Close();
}
catch(Exception e)
{
    // do something with the exception
}

還有一個選項可以讓您一次在頁面中嵌入所有圖像,但這涉及使用數據Uris,這會減慢頁面的加載速度。 首先,您必須以字節數組的形式從數據庫中獲取圖像,然后使用base64對該字節數組進行編碼。

byte[] img = GetImage(id);
string imageSource = "<img src=\"data:image/jpeg;base64," +  Convert.ToBase64String(img)  + " />";

不建議將其用於較大的圖像,因為頁面將等待所有圖像下載完畢后再顯示其中的任何圖像。 您的用戶可能會因為等待時間過長而感到沮喪。 但是,它可以處理較小的圖像。 只要明智地提供圖像即可。 如果它們是幾兆字節,我將不會使用此方法。 同樣,啞劇類型將需要根據圖像類型進行調整。

使用服務器映像控件:

<asp:Image runat="server" ID="img1" ImageUrl="getimage.ashx?id=1" />
<asp:Image runat="server" ID="img1" ImageUrl="getimage.ashx?id=2" />
<asp:Image runat="server" ID="img1" ImageUrl="getimage.ashx?id=3" />

AND內部處理程序:

string id = context.Request.QueryString["id"];
DataRow dr = GetImageById(id);
Byte[] myImg = (Byte[])dr["Image"];
context.Response.ContentType = "image/jpeg"; 
context.Response.BinaryWrite(myImg);
context.Response.Flush();
context.Response.Close(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM