我有一个问题 - 如何在浏览器中显示图像而不在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
答案 0 :(得分:0)
这就是我在我的一个项目中的表现:看看src部分
<p><a href='<%#"TheObject.aspx?O=" + Eval("ID") %>'><img runat="server" visible='<%#Eval("AttachmentID") != DBNull.Value %>' class="objPicture1" alt='<%Eval("Title") %>' width="340" height="260" src='<%#"~/Attachment.aspx?ID=" + Eval("AttachmentID")%>' /></a></p>
在Attachment.aspx中,您有以下代码:
protected void Page_Load(object sender, EventArgs e)
{
Guid objID = //take the ID of the object ?ID=""
DataRow attachmentRow = //fetch DataRow of the Attachment from Database
if (attachmentRow == null)
return;
Response.ContentType = attachmentRow["ContentType"].ToString();// value of this is image/gif or image/jpeg and etc.
Response.BinaryWrite((byte[])attachmentRow["Data"]); // Data is type image in my case
Response.End();
}
答案 1 :(得分:0)
看起来你正在以错误的方式创建Base64String
。您正在向其附加不应该起作用的文件名。试试看。
string image_string = Convert.ToBase64String((byte[])sdr["Data"]);
直接将其分配给ImageUrl
。这里不需要使用MemoryStream
。
imageButton.ImageUrl = "data:image/jpg;base64," + image_string;