zoukankan      html  css  js  c++  java
  • .net core使用ViewComponent将页面图片转码成base64

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Caching.Memory;
    
    namespace MyPorject.MVC.ViewComponents
    {
        public class ImgToBase64ViewComponent : ViewComponent
        {
            private readonly IHostingEnvironment _hostingEnvironment;
            private readonly IMemoryCache _memoryCache;
            public ImgToBase64ViewComponent(IHostingEnvironment hostingEnvironment, IMemoryCache memoryCache)
            {
                _hostingEnvironment = hostingEnvironment;
                _memoryCache = memoryCache;
            }
    
            public async Task InvokeAsync(string src)
            {
                string cacheKey = src;
                string result = await _memoryCache.GetOrCreateAsync(cacheKey, async entry =>
                  {
                      string webRootPath = _hostingEnvironment.WebRootPath;
                      string path = webRootPath + @"" + src.TrimStart('~').TrimStart('/').Replace(@"/", @"").ToString();
    
                      try
                      {
                          using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                          {
                              var byteArray = new byte[fs.Length];
                              await fs.ReadAsync(byteArray, 0, byteArray.Length);
                              result = "data:image/jpeg;base64," + Convert.ToBase64String(byteArray);
                          }
                      }
                      catch (Exception ex)
                      {
                          result = ex.Message;
                      }
                      return await Task.FromResult(result);
                  });
                return View("", result);
            }
        }
    }

     添加default.cshtml

     使用方法:

    将原来src中改成Component.InvokeAsync 就可以使用了
    

     

    效果如图:

  • 相关阅读:
    用“Keras”11行代码构建CNN
    技术 | 使用深度学习检测DGA(域名生成算法)
    未来的超级智能网络攻击需要AI竞技俱乐部来拯救
    开源中国的代码托管
    Hello Java !
    15-include的使用
    14-递归函数
    13-函数的调用
    12-函数的返回值
    11-函数的参数
  • 原文地址:https://www.cnblogs.com/WNpursue/p/10447208.html
Copyright © 2011-2022 走看看