using Microsoft.AspNetCore.Mvc;
using System;
namespace YourNamespace.Controllers
{
public class ImageController : Controller
{
public IActionResult Index()
{
// 这里是你的 Base64 字符串,实际使用时可以从数据库、文件或其他地方获取
string base64String = "your base64 encoded image string here";
ViewBag.Base64Image = base64String;
return View();
}
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Base64 Image Display</title>
</head>
<body>
<div>
<img src="data:image/png;base64,@ViewBag.Base64Image" alt="Base64 Image" />
</div>
</body>
</html>
-
Controller 部分:
ImageController
是一个控制器类,继承自Controller
。Index
方法是一个动作方法,它将被用来处理对Index
页面的请求。string base64String = "your base64 encoded image string here";
:你需要将your base64 encoded image string here
替换为实际的 Base64 编码的图像字符串。这个字符串可以从数据库、文件或其他数据源中获取。ViewBag.Base64Image = base64String;
:使用ViewBag
将 Base64 字符串传递给视图。
-
View 部分:
@{ Layout = null; }
:设置布局为null
,表示该视图不使用布局文件。<img src="data:image/png;base64,@ViewBag.Base64Image" alt="Base64 Image" />
:使用img
标签显示图像。data:image/png;base64,
是一个数据 URI 方案,它告诉浏览器该图像是一个 Base64 编码的 PNG 图像。@ViewBag.Base64Image
是使用 Razor 语法将ViewBag
中的 Base64 字符串插入到src
属性中。