如何显示二进制byte[]数组而不是 base64?

XuDong Peng-MSFT 10,181 信誉分 Microsoft 供应商
2024-01-30T07:44:39.17+00:00

我正在尝试在 ASP.NET MVC 中显示 byte[] 数组图像。我不想在图像会话上浪费 CPU 资源。 我在视图上显示图像列表,但不想将它们转换为 Base64。 SQL Server 不支持以该格式保存。 所以,这是我的实现,但它填充整个页面来加载一张图像,而不加载所有其他图像。 这是代码:

Public stream GetBinaryImage(byte[] buffer, string ContentType) 
{ 
      Httpcontext.Current.Response.ContentType = ContentType; 
      Httpcontext.Current.Response.BinaryWrite(buffer); 
      return Httpcontext.Current.Response.OutputStream; 
}

Note: 该问题整理于:Display binary byte[] array instead of base64

ASP.NET
ASP.NET
.NET Framework 中一套用于生成 Web 应用程序和 XML Web 服务的技术。
17 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Zhi Lv - MSFT 32,036 信誉分 Microsoft 供应商
    2024-01-30T09:08:09.8833333+00:00

    你好,

    我假设图像已经在 byte[] 数组中。 其余的很简单,从 MVC 操作返回 FileResult 并利用 Controller.File() 方法,如下所示:

            public class FileController : Controller
            {
                public ActionResult Index()
                {
                    return View();
                }
                // GET: GetTele  
                public FileResult GetTele()
                {
                    byte[] fileBuffer = System.IO.File.ReadAllBytes(Server.MapPath("~/images/tele.jpg"));
                    return File(fileBuffer, "image/jpg");
                }
            }
    

    显示图像的 Index 视图,代码如下:

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <div>
        <img src="/File/GetTele" alt="Telecaster" />
    </div> 
    
    

    如果答案是正确的解决方案,请单击“接受答案”并请投赞成票。如果您对此答案有其他疑问,请点击“评论”。
    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。
    最好的问候

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助