【发布时间】:2014-11-12 15:12:33
【问题描述】:
我有一个问题-如何在浏览器中显示图像而不将图像保存在 Temp 文件夹中?甚至可能吗?我的代码必须从数据库中读取图像并在网站中显示图像。我实际上尝试从数据库转换数据,但我不知道我想做什么。 我也尝试使用“imageHandlers”、“FileStream”、“Base64StringToBitmap”,但仍然没有任何效果...... 请编写示例代码或修改我的代码。
private void LoadImages()
{
ImageButton imageButton = new ImageButton();
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name, Data from tblFiles WHERE email = @CurrentUser";
cmd.Parameters.Add("@CurrentUser", SqlDbType.NVarChar);
cmd.Parameters["@CurrentUser"].Value = User.Identity.Name;
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
sdr.Read();
string fileName = sdr["Name"].ToString();
FileInfo fi = new FileInfo(fileName);
byte[] byte_image_string = ((byte[])sdr["Data"]);
string image_string = Convert.ToBase64String((byte[])sdr["Data"]) + fi.Name;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
Panel1.Controls.Add(imageButton);
System.Drawing.Image newImage;
if (byte_image_string != null)
{
using (MemoryStream stream = new MemoryStream(byte_image_string))
{
newImage = System.Drawing.Image.FromStream(stream);
//I want here display image to browser without saving
//string newPhoto = "";
//newImage.Save(newPhoto);
imageButton.ImageUrl = "data:image/jpg;base64," + newPhoto;
}
}
conn.Close();
}
}
}
}
}
我来自数据库的示例图像代码:
0xFFD8FFE000104A46494600010100000100010000FFE1018C45786966000049492A0008000000020031010200070000002600000069870400010000002E00000000000000476F6F676C6500000500009007000400000030323230099007000B0000007000000086920700080100007B00000002A00400010000006F02000003A0 P>
【问题讨论】:
-
你可以尝试将img文件显示为ImageUrl后删除。
-
只有在网站上显示图片的方法吗?
-
检查我的答案并告诉我你是否同意。
标签: c# sql asp.net database type-conversion