How to utilize the common image resources in MVC

泪湿孤枕 提交于 2020-01-11 06:55:09

问题


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?


回答1:


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" })' />

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" />

A good way to implement this might be to use a Razor helper, to enable the more straightforward syntax in the view @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):

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


来源:https://stackoverflow.com/questions/12523098/how-to-utilize-the-common-image-resources-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!