我想从DLL /连接项目访问并返回资源图像。
(它是一个文件,具有Resource
的构建动作)。它没有在属性/资源中列出,因为文件夹中有数百个。
我的想法是我可以调用图像控制器。
public ImageResult Display(string resourcePath){
Uri uri = new Uri("pack://application:,,,/ProjectName;component/Images/Vectors/" + resourcePath, UriKind.Absolute);
// What goes here??
}
问题是我不知道如何将URI转换为MVC5中的图像。
我希望能够从视图中调用它。使用<img>
标记的url属性
我想你可以尝试使用WebClient.DownloadData()
方法从指定的URI下载图像作为字节数组,然后用Convert.ToBase64String()
将其转换为Base64格式,并使用viewmodel中的字符串属性将其显示在<img>
标签上作为src
属性值,下面是一个显示示例图片:
Viewmodel示例
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));
相关问题: