简体   繁体   English

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

[英]How to load image from Content folder in ASP.NET MVC5?

I'm having a WebAPI project (MVC5) and just put an image in Content/Images. 我有一个WebAPI项目(MVC5),只是将一个图像放在Content / Images中。 I'd like to load this image in C# and edit some stuff on runtime: 我想在C#中加载此图像并在运行时编辑一些内容:

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

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

This does not work unfortunatly, I'm getting an exception: System.ArgumentException - >Parameter is not valid. 不幸的是,这无法正常工作,我遇到一个异常:System.ArgumentException-> Parameter无效。

My setup (code view left, solution explorer right): 我的设置(左侧为代码视图,右侧为解决方案资源管理器): 在此处输入图片说明

  1. Use an Application-root-relative filename (add a ~ character): ~/content/Images/Image.png . 使用相对于应用程序根目录的文件名(添加~字符): ~/content/Images/Image.png
  2. Use Server.MapPath to convert the Application-root-relative filename to an absolute filename. 使用Server.MapPath将相对于应用程序根目录的文件名转换为绝对文件名。
  3. Pass this absolute filename into the Bitmap constructor. 将此绝对文件名传递给Bitmap构造函数。

Like so: 像这样:

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM