C#MVC使用二進制流顯示圖片


關於顯示圖片的最好方法當然是img 的src直接指向地址,簡單實用。但是有時候也會使用到使用圖片流顯示圖片的方法。實現也比較簡單(在C# mvc中,java的不了解)。具體如下:

1.前台cshtml部分

添加img 標簽,其地址指向后台的返回圖片流的方法。

<img src="@Url.Action("ShowImage","ShowImgFromImgByte",new { id="5"})" /><span id="__kindeditor_bookmark_start_14__"></span>

@Url.Action方法有三個參數,方法名、Control名稱、方法參數(參數類型不用寫)

2.后台control部分

/// <summary>
/// 本地圖片
 /// </summary>
/// <returns></returns>
public FileResult ShowImage(string id)
{
    string _path = string.Concat(System.AppDomain.CurrentDomain.BaseDirectory, "Content\\images\\longmao.png");
    FileStream fs = new FileStream(_path, FileMode.Open);
    byte[] byData = new byte[fs.Length];
    fs.Read(byData, 0, byData.Length);
    fs.Close();
    return File(byData, "image/jpg");
}

其中返加值類型為FileResult,不是我們常見的ActionResult,同樣的,return時也是return File().關於mvc的不同返回類型,大家可以上網了解下。

特別說明,這種圖片的展示方法不推薦,使用起來相對比較麻煩。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM