ASP.NET-如何在浏览器中显示图像而不在临时中保存图像
本文关键字:图像 保存 显示 NET- 浏览器 ASP 显示图 | 更新日期: 2023-09-27 18:22:16
我有一个问题-如何在浏览器中显示图像而不将图像保存在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();
}
}
}
}
}
我的数据库图像代码示例:
0xFFD8FFE0000104A46494600010100000100010000FFE1018C45786966000049492A000000000200310102000700000026000000698704000010000002E00000000000000476F6F676C6500000000900700000030323230099007000000007000000008692070000000007B00000002A0040010000000006F000003A0
我在一个项目中就是这样做的:Look src part
<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();
}
看起来您以错误的方式创建Base64String
。您正在将文件名附加到它上,这不应该起作用。试着跟随。
string image_string = Convert.ToBase64String((byte[])sdr["Data"]);
直接分配给ImageUrl
。这里不需要使用CCD_ 3。
imageButton.ImageUrl = "data:image/jpg;base64," + image_string;