如何从ASP.NET MVC5中的Content文件夹加载图像?

时间:2015-04-07 18:02:12

标签: c# asp.net image

我有一个WebAPI项目(MVC5),只是在Content / Images中放置一个图像。我想在C#中加载这个图像并在运行时编辑一些东西:

string originalFileName = "/Content/Images/Image.png";

Bitmap bitmap = new Bitmap(originalFileName);
Graphics g = Graphics.FromImage(bitmap);

这不方便,我得到一个异常:System.ArgumentException - >参数无效。

我的设置(左侧代码视图,右侧解决方案资源管理器): enter image description here

1 个答案:

答案 0 :(得分:2)

  1. 使用Application-root-relative文件名(添加~个字符):~/content/Images/Image.png
  2. 使用Server.MapPath将Application-root-relative文件名转换为绝对文件名。
  3. 将此绝对文件名传递给Bitmap构造函数。
  4. 像这样:

    String fileName = "~/Content/Images/Image.png";
    fileName = Server.MapPath( fileName );
    if( File.Exists( fileName ) ) {
        using( Bitmap bmp = new Bitmap( fileName ) )
        using( Graphics g = Graphics.FromImage( bmp ) ) {
            // do stuff here
        }
    }