我想通过将图像转换为base64字符串来在浏览器上显示图像。 转换方法非常简单如下
string convertedfile = Convert.ToBase64String(fileData);
base64字符串
<img src="data:image/jpeg;base64,DQoaCgAAAA1JSERSAAAAFAAAABQIBgAAAI2JHQ0AAAABc1JHQgCuzhzpAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAl2cEFnAAAAgAAAAIAAMOExmgAAAAZiS0dEAAAAAAAA+UO7fwAAACJ6VFh0U29mdHdhcmUAAHjaKy8v18vMyy5OTixI1csvSgcANtgGWBBTylwAAADzSURBVDhPY/wPBAxUBExUNAts1KiBlIfoaBhiD8N1NycwHLi/mqgAJhiGp15uYtj1aCbD5OMZDDdenSJsKCjr4QJvfzz977GZAS5t2Mvw//P3j/i0/EeoRlP299/v/667UaX//vv7X6MOpxawCThlw04z/H//8zmGa158fPDfsBq3oYzYSpusW8IMPgJVDEa8gQxff31k+P8PaPE/Bob/fxkYuNkEGfZeXskwZ1cnw6Hm9xhhimHgn/8/Gea9SGP485OR4fu37wx/fzIw/PkBwTA2818OIP8fQ0P4XAY2FjYUQ7G6kHBU4lZBMNmQavjgNxAArnYq4oN7ItkAAAAASUVORK5CYII=" alt="Original File"/>
由于某种原因,我的浏览器无法显示它。我必须在IIS中设置任何MIME类型吗?或者可能是什么问题?
修改 将文件数据写入SQL
Stream fs = imgUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//string base64String = Convert.ToBase64String(bytes);
//imgPicture.Src = "data:image/png;base64," + base64String;
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
using (SqlCommand cmd = new SqlCommand("update tbEHUsers set photo=@binaryValue where UserID=101", conn))
{
// Replace 8000, below, with the correct size of the field
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, -1).Value = bytes;
cmd.ExecuteNonQuery();
}
conn.Close();
我从SQL获取图像数据的方法(列数据类型varbinary)
byte[] fileData =null;
using (SqlDataReader rdr = CMD.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (rdr.Read())
{
// For some reason the data being returned is blank
// When I run it in SQL I get data being returned.
fileData = (byte[])rdr.GetValue(0);
using (System.IO.FileStream fs = new System.IO.FileStream("D:\\Testing.jpg", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
{
bw.Write(fileData);
bw.Close();
}
}
}
rdr.Close();
}
答案 0 :(得分:3)
您拥有的数据根本不是PNG图像。将其交换为真实的PNG图像,它将起作用。
例如,10x10红色正方形:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAXSURBVChTY/jPwPCfGDyqEC+mtkKG/wCSw8c5Wcde4gAAAABJRU5ErkJggg==">
以下是base64格式的原始图片:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAUABQDASIAAhEBAxEB/8QAGAABAAMBAAAAAAAAAAAAAAAAAAQFBgf/xAAiEAABBAEDBQEAAAAAAAAAAAABAAIDBBEFEkETITFDUbH/xAAWAQEBAQAAAAAAAAAAAAAAAAAAAgP/xAAZEQEBAQADAAAAAAAAAAAAAAAAAQIDERL/2gAMAwEAAhEDEQA/AO/oot+62jW6hALnO2MDjgFx+ngck/pwFUQaxFSuwwyaky7HaeGEtxuilPjDR6ye3JacZJBJbneXM15TdyXpoURFooREQEREH//Z">