MVC下 把数据库中的byte[]值保存成图片,并显示在view页面

MVC下 把数据库中的byte[]值转成图片,并显示在view页面

controller中的action方法

//显示图片
[AllowAnonymous]
public ActionResult ShowImage(int id)
{
   LogHandler.Handler.WriteLog("UploadImage   id:" + id);
   try
   {
     EncyclopediaService service = new EncyclopediaService();
     ImageByteResultModel result = service.GetImageByte(id);
     if (result.IsSucess == false)//数据库中没有byte[]数据时的分支,没有图片数据时,显示一张默认图片
     {
       string path = System.Environment.CurrentDirectory;//非Web程序
       if (System.Environment.CurrentDirectory != AppDomain.CurrentDomain.BaseDirectory)
       {
         path = AppDomain.CurrentDomain.BaseDirectory;//asp.net 程序
         path += "Image\DefaultImage.gif";//相对路径
         return File(System.IO.File.ReadAllBytes(path), @"image/jpeg");
        }  
      }
      byte[] imageByte = result.ImageByte;
      return File(imageByte, @"image/jpeg");
   }
   catch (Exception ex)
   {
      LogHandler.Handler.WriteLog(ex.ToString());
   }
   return View("error");
}

view中的调用

<img src="/UploadImage/ShowImage?id=12"  />

或者

model.ImagePath ="/UploadImage/ShowImage?id=" + item.WholeImageId;

<img src=' + payMachineImgArr[i].ImagePath + '  style="position: relative; 45%;" />

原文地址:https://www.cnblogs.com/lijingran/p/6305602.html