【问题标题】:The binary image can't display on view asp.net core 2.x二进制图像无法在视图 asp.net core 2.x 上显示
【发布时间】:2018-10-02 15:19:15
【问题描述】:

我将图像上传到 byte[] 格式的表格中。我的问题是,当我在视图上检索它时,图像不会显示出来。

型号

{
   public byte[] image {get; set;}
}

控制器

public async Task<IActionResult> Create(Profile profile, IFormFile image)
{
    if (ModelState.IsValid)
    {
        using (var memoryStream = new MemoryStream())
        {
            image.CopyTo(memoryStream);
            profile.image = memoryStream.ToArray();
        }

        _context.Add(image);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(image);
}

查看

<img src="@item.image" />

【问题讨论】:

    标签: asp.net-core-mvc-2.0 asp.net-core-mvc-2.1


    【解决方案1】:

    您不能简单地将字节数组转储为 HTML 图像标记的源。它必须是一个 URI。这通常意味着您需要一个从数据库中检索图像数据并将其作为文件返回的操作:

    [HttpGet("profileimage")]
    public async Task<IActionResult> GetProfileImage(int profileId)
    {
        var profile = _context.Profiles.FindAsync(profileId);
        if (profile?.image == null) return NotFound();
    
        return File(profile.image, "image/jpeg");
    }
    

    然后,您可以执行以下操作:

     <img src="@Url.Action("GetProfileImage", new { profileId = item.Id })" />
    

    或者,您可以使用数据 URI。但是,这会导致整个图像数据都包含在您的 HTML 文档中,从而增加文档的整体下载时间并延迟渲染。此外,数据 URI 必须是 Base64 编码的,这有效地将图像大小增加了大约 1.5 倍。对于小而简单的图像,这没什么大不了的,但是对于较大的图像,您绝对应该避免这种方法。无论如何,这样做看起来像:

    <img src="data:image/jpeg;base64,@Convert.ToBase64String(item.image)" />
    

    【讨论】:

    • 在您的操作中没有 Profile 模型的情况下如何访问 Image 属性,出现错误
    • 感谢@Chris Pratt,如果没有 GetProfileImage 操作,图像将通过转换后的 64、img 标签显示。
    • 如何在 foreach 循环之外获取此图像?我想将它存储在不同地方的变量显示中。
    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    相关资源
    最近更新 更多