【问题标题】:MVC Access Resource imageMVC 访问资源镜像
【发布时间】:2019-08-12 11:47:32
【问题描述】:

我想从 DLL /connected 项目访问并返回资源图像。

(它是一个文件,构建操作为Resource)。它没有在属性/资源中列出,因为文件夹中有数百个。

这个想法是我可以调用一个图像控制器。

public ImageResult Display(string resourcePath){
     Uri uri = new Uri("pack://application:,,,/ProjectName;component/Images/Vectors/" + resourcePath, UriKind.Absolute);

     // What goes here??
}

问题是我不知道如何在 MVC5 中将 URI 转换为图像。

我希望能够从视图中调用它。使用<img>标签的url属性

【问题讨论】:

    标签: asp.net-mvc image model-view-controller asp.net-mvc-5 resources


    【解决方案1】:

    我认为您可以尝试WebClient.DownloadData() 方法从指定的URI 将图像下载为字节数组,然后使用Convert.ToBase64String() 将其转换为Base64 格式,并使用视图模型中的字符串属性将其显示在<img> 标记上为@ 987654327@属性值,下面是显示图片的例子:

    视图模型示例

    public class ViewModel
    {
        // other properties
    
        // used to pass image into src attribute of img tag
        public string ImageData { get; set; }
    }
    

    控制器动作

    public ActionResult Display(string resourcePath)
    {
         Uri uri = new Uri("pack://application:,,,/ProjectName;component/Images/Vectors/" + resourcePath, UriKind.Absolute);
    
         using (var wc = new System.Net.WebClient())
         {
             // download URI resource as byte array
             byte[] image = wc.DownloadData(uri);
    
             // get image extension
             string path = string.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath);
             string extension = System.IO.Path.GetExtension(path).Replace(".", "");
    
             // assign image to viewmodel property as Base64 string format
             var model = new ViewModel();
    
             model.ImageData = string.Format("data:image/{0};base64,{1}", extension, Convert.ToBase64String(image));
    
             return View(model);
         }
    }
    

    查看

    @model ViewModel
    
    <img src="@Model.ImageData" ... />
    

    补充说明:

    如果你已经知道资源 URI 的扩展名,你可以直接使用它而不是使用 Path.GetExtension,这里是一个 JPG 格式的例子:

    model.ImageData = string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
    

    相关问题:

    Image to byte array from a url

    MVC How to display a byte array image from model

    【讨论】:

      【解决方案2】:

      请务必注册 pack:// 方案,因为它不会像在 WPF 应用程序中那样自动注册到 MVC 应用程序中。

      在此示例代码中,Blarn0 是我的模型类中的公共属性,以确保在发布配置中发布代码时不会优化对 PackUriHelper.UriSchemePack 属性的访问。我敢肯定,在以后的 C# 版本中,人们可以为此目的使用丢弃。

      const string scheme = "pack";
      if (!UriParser.IsKnownScheme(scheme))
         Blarn0 = PackUriHelper.UriSchemePack;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2014-11-20
        • 2013-08-02
        相关资源
        最近更新 更多