C# ASP MVC无法在视图中显示图像
所以我得到了一个字节[]形状的图像,我想显示在我的视图中 这是我的图像模型:C# ASP MVC无法在视图中显示图像,c#,asp.net-mvc,sqlite,C#,Asp.net Mvc,Sqlite,所以我得到了一个字节[]形状的图像,我想显示在我的视图中 这是我的图像模型: public class ImageModel { public Byte[] imageFirst { get; set; } } 这是我的控制器从数据库中选择图像: public ActionResult Image() { string cs = "Data Source=" + Environment.CurrentDirectory + "\\
public class ImageModel
{
public Byte[] imageFirst { get; set; }
}
这是我的控制器从数据库中选择图像:
public ActionResult Image()
{
string cs = "Data Source=" + Environment.CurrentDirectory + "\\ImageDB.db";
using (SQLiteConnection con = new SQLiteConnection(cs))
{
var listOfImages = new List<ImageModel>();
string stm = "SELECT * FROM Image";
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listOfImages.Add(new ImageModel
{
imageFirst = Serialize(rdr["image_first"]),
});
}
rdr.Close();
Images = listOfImages;
}
}
con.Close();
}
return View(Images);
}
public static byte[] Serialize(object obj)
{
var binaryFormatter = new BinaryFormatter();
var ms = new MemoryStream();
binaryFormatter.Serialize(ms, obj);
return ms.ToArray();
}
这是当我试图在视图中显示图像时:
<img src="data:image/jpg;base64,@(Convert.ToBase64String(@item.imageFirst))" width="300px"/>
但我得到的只是这个图标:
看在我的份上,我想不出为什么它不能被展示出来。图像被存储为数据库中的一个blob,但现在我希望它们只是光盘上的图像文件,因为这样可以更容易地将它们附加到视图中。您使用的浏览器。IE对数据URI有大小限制,我认为是32KB。转换为base64后图像字符串的大小是多少。假设imageFirst属性是有效的图像字节数组,您可能需要在输出中包含html raw模式:
<img src="data:image/jpg;base64,@Html.Raw(Convert.ToBase64String(item.imageFirst))" width="300px"/>
另外,使用item而不是@item,因为您已经在@中,或者在示例@Html.Raw中。您的代码有点混乱。您正在将模型添加到listOfSlides,但返回的视图中包含listOfImages,它似乎从未填充过。是的,这确实有点令人困惑!现在已经修好了。什么是rdr[image_first]?图像是如何存储到此字段中的?它是SQLiteDataReader从数据库列image_读取的一个实例,其中图像以字节[]的形式存储。然后不是双重编码吗?序列化步骤是否必要?