如何利用MVC中常见的图像资源 [英] How to utilize the common image resources in MVC

查看:101
本文介绍了如何利用MVC中常见的图像资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个ASP.NET MVC3和4个网站。所有网站都使用的是单独的一个库相同的资源。资源是.resx文件。
我想使用这些资源的图像,我的这些网站内的HTML。
我没有使用之前,所以不知道什么是与他们一起工作的好方法RESX文件。
我认为,我可能会创建一个服务从正确的资源文件中提供正确的形象,但我想应该有一个更好的办法。
我的问题是什么是使用这些图片来自RESX文件是个好办法,可能是它是不是真的好存储在图像RESX?

I have several ASP.NET MVC3 and 4 web sites. All sites are using the same resources that are separate to a library. Resources are .resx files. I'd like to use images from these resource in my html inside these sites. I wasn't using resx files before so not sure what is a good way to work with them. I think that I might create a service to provide right image from right resource file, but i guess there should be a better way. My question is what is a good way to use these images from resx files and might be it is not really good to store images in a resx?

推荐答案

一个简单的方法做,这是一个 FileStreamResult 操作添加到控制器,它应该会返回图像的基础上的资源键。

One easy way to do this is to add a FileStreamResult action to the controller, which should return the image based on the resource key.

public FileStreamResult Image(string key)
{
    var bitmap = (Bitmap)Resources.Images.ResourceManager.GetObject(key);
    MemoryStream stream = new MemoryStream();
    bitmap.Save(stream, ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(stream, "image/png");
}

现在你应该能够从视图访问它是这样的:

Now you should be able to access it from your view like this:

<img src='@Url.Action("Image", "MyController", new { key = "Image1" })' />


这是另一种方式(可以只使用视图来完成)是创建一个基地64 CS codeD字符串。


An alternate way (which can be done using only the view) is to create a base 64 encoded string.

@{
    var stream = new MemoryStream();
    var bitmap = Resources.Images.ResourceManager.GetObject("Image1") as System.Drawing.Bitmap;
    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    string base64 = Convert.ToBase64String(stream.ToArray());
}

<img src="data:image/gif;base64,@base64" />

实现这个可能是用剃刀帮手,使视图更直接的语法的一个好办法 @ Html.GetImageFor(Resources.Images.Image1,ALT)

public static MvcHtmlString GetImageFor(this HtmlHelper helper, Bitmap bitmap, string AltText = "")
{
    MemoryStream stream = new MemoryStream();
    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    string base64 = Convert.ToBase64String(stream.ToArray());

    return new MvcHtmlString(
        string.Format("<img src='data:image/gif;base64,{0}' alt='{1}' />",
            base64, AltText)
    );
}


<子>
注意:


Note: The properties on the .ResX files should be set as follows (as normal for MVC projects):


  • <子>设置 CustomTool 来的 PublicResXFile codeGenerator

  • <子>设置自定义工具命名空间来的资源

  • set CustomTool to PublicResXFileCodeGenerator
  • set Custom Tool Namespace to Resources

这篇关于如何利用MVC中常见的图像资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆