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; width:45%;" />