<img src=data:image/jpg;base64," + (Base64编码的图片字符串)+ "></img>
前台写成这样的话 那后台代码应该怎么写呢 ?麻烦以代码告知 谢谢。
Action:
public ActionResult Index()
{
using (Image image = Image.FromFile(Server.MapPath("~/image/abc.png")))
{
using (MemoryStream ms=new MemoryStream())
{
image.Save(ms,image.RawFormat);
byte[] data = ms.ToArray();
ViewBag.Img = Convert.ToBase64String(data);
}
}
return View();
}
View:
<img src=data:image/png;base64,@ViewBag.Img />
ViewBag怎么定义呢?
ViewBag怎么定义呢?
@撞到南墙拆了继续走: ViewBag 是动态类型,可直接调用,执行时解析。
@月光木叶:
public UpGoodsModel GetDownPicture(UpGoodsCondition condition) { //bool isSelectedEleData = "0".Equals(condition.GoodsNumber); var rolecode = _ProjectDataContext.UpGoodsModel.Where(x => x.GoodSNumber.Equals(condition.GoodSNumber)).ToList().FirstOrDefault(); MemoryStream memStream = new MemoryStream(); //byte[] data = memStream.ToArray(); //rolecode.Doc = Convert.ToBase64String(data.ToString()); byte[] img = rolecode.Doc; byte[] bytes = memStream.GetBuffer(); string base64 = Convert.ToBase64String(bytes); return rolecode; }
麻烦看看这样 对么?
@撞到南墙拆了继续走: 如果 rolecode.Doc
就是图片数据的话
public string GetDownPicture(UpGoodsCondition condition)
{
var rolecode = _ProjectDataContext.UpGoodsModel.Where(x => x.GoodSNumber.Equals(condition.GoodSNumber)).ToList().FirstOrDefault();
byte[] img = rolecode.Doc;
return Convert.ToBase64String(img);
}
@月光木叶: 好的 感谢。
using (Image image = Image.FromFile(Path)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); return base64String; } }
ref:http://stackoverflow.com/questions/21325661/convert-image-path-to-base64-string
是我没说清楚 是二进制转换为base64,数据库中存的不是路径,是二进制格式 这样的话也可以用么?
@撞到南墙拆了继续走: 如果你数据库存放的是二进制更好了啊,直接转为byte[],下面代码就一样了。
道理一样,我发的代码是把图片转为stream,然后转为字节组,然后转base64.
你现在需要的是直接把你数据库的二进制转为字节组,然后转base64
string _cnnString = System.Configuration.ConfigurationManager.ConnectionStrings["cnxstring"].ToString(); SqlConnection myConnection = new SqlConnection(_cnnString); string sql = "SELECT Photo FROM [Employees] WHERE [EmployeeID] = @ID"; SqlCommand cmd = new SqlCommand(sql, myConnection); cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"]; myConnection.Open(); byte[] pict = (byte[])cmd.ExecuteScalar();