如何从SQL Server数据库中检索图像。
我有一个代码将图像转换为字节数组并将其存储到数据库中。但我想基于id从数据库中检索图像。下面是将图像转换为字节数组的代码。
------------------------------ --------------------
I have a code that convert image into array of bytes and store it into database. But I want to retrieve an image from database based on id. Below is the code to convert image into array of bytes.
--------------------------------------------------
private void convertImage()
{
if (FLUImg.HasFile)
{
try
{
int length = FLUImg.PostedFile.ContentLength;
arrImg = new byte[length];
HttpPostedFile img = FLUImg.PostedFile;
img.InputStream.Read(arrImg, 0, length);
}
catch (Exception ex)
{
Response.Write("Error Uploading Image" + ex.ToString());
}
}
else
{
Response.Write("Please select an image");
}
}
------------------------- ------------------
这里是使用数据集和datareader从数据库中检索图像的代码。但是图片没有加载。
----------------------------------- --------------
-------------------------------------------
here is the code that retrieve image from database using dataset and datareader . But the image does not load.
-------------------------------------------------
public void SportsMain()
{
try
{
con.Open();
da = new SqlDataAdapter("SELECT TOP 1 * from tbl_news_details where cid=2 order by nid desc", con);
DataTable dt = new DataTable();
da.Fill(dt);
DataListSports.DataSource = dt;
DataListSports.DataBind();
con.Close();
}
catch (Exception ex) { }
}
-----------------------------------------
Datareader代码
----------------------------------------- -
-----------------------------------------
Datareader Code
------------------------------------------
con.open();
ss = "SELECT * FROM tbl_news_details WHERE nid='" + max + "'";
cmd = new SqlCommand(ss, con);
dr = cmd.ExecuteReader();
dr.Read();
if(dr.HasRows)
{
num1 = Convert.ToInt16(dr["nid"]);
lblTitle1.Text = dr["title"].ToString();
img1 = (Image)dr["img"];
}
dr.Close();
con.Close();
从数据库中获取字节数组时,可以将其写入文件并使用该文件作为图像的ImageUrl。
所以类似于:
When fetching the byte array from the database, you can write it into a file and the use that file as the ImageUrl for the image.
So something like:
byte[] imageBytes = dr["img"] as byte[];
string fileName = @"SOME LOCATION\" + System.DateTime.Now.Ticks.ToString() + ".jpg"; // whatever is the proper location and type for the file
using (System.IO.FileStream imageFile = new System.IO.FileStream(fileName, System.IO.FileMode.CreateNew)) {
imageFile.Write(imageBytes, 0, imageBytes.Length);
imageFile.Flush();
imageFile.Close();
}
img1.ImageUrl = fileName;