我知道在Windows窗体中显示mysql blob图像的方法。
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select logo from mcs_institude where id = 1";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
pictureBox1.Image = new Bitmap(new MemoryStream((byte[])Reader.GetValue(0)));
}
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in Get_ImageFormDB"+ ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
但现在我正在做一个asp.net项目。在此图像中没有图像属性,。
command = connection.CreateCommand();
command.CommandText = "Select FO_Roomdet_Image from fo_roomtype where FO_Roomdet_Id=1";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
Image1.ImageUrl = new MemoryStream((byte[])Reader.GetValue(0));
}
connection.Close();
当我在asp.net中尝试这个时,它会出错。
错误1无法将类型'System.IO.MemoryStream'隐式转换为 '字符串'
我如何解决这个问题。并获取mysql blob图像只显示在asp.net图像控件中。
请帮助我。答案 0 :(得分:2)
您尝试做的事情没有意义:尝试显示图片的浏览器需要知道从哪里下载。
您应该设置一个专门用于图像生成的特殊aspx页面,例如GetImage.aspx。
然后,您的主页面将包含指向此图像生成页面的img html标记:
<img src="/GetImage.aspx?id=your_image_id"/>
然后,在GetImage.aspx中,您根据其ID(从URL参数获取)从DB检索图像。代码类似于:
command = connection.CreateCommand();
command.CommandText = "Select FO_Roomdet_Image from fo_roomtype where FO_Roomdet_Id=1"; // or dynamically fetch id with Request.QueryString and properly escape it
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
Response.ContentType = "image/jpeg"; // if your image is a jpeg of course
Response.BinaryWrite((byte[])Reader.GetValue(0));
}
connection.Close();
答案 1 :(得分:0)
嗯,这绝对不是最简单的答案。 每次使用时,您都不需要创建额外的aspx文件来生成图像并重新生成。
您实际上可以通过它的字节数组将图像文件嵌入到html标记语言中。
您需要做的就是从数据库中获取BLOB字节数组并使用:
<img src="data:image/png;base64,<%= System.Convert.ToBase64String((byte[])dr["img"])%>" />
...其中dr是从DataSet对象获取的DataRow。
我已经在Internet Explorer 8和所有现代浏览器中对其进行了测试,并且可以正常运行。