0

I'm having a WebAPI project (MVC5) and just put an image in Content/Images. I'd like to load this image in C# and edit some stuff on runtime:

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.

My setup (code view left, solution explorer right): enter image description here

1 Answer 1

3
  1. Use an Application-root-relative filename (add a ~ character): ~/content/Images/Image.png.
  2. Use Server.MapPath to convert the Application-root-relative filename to an absolute filename.
  3. Pass this absolute filename into the Bitmap constructor.

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Server.MapPath does not seem to exist in the namespace? I'm only getting Microsoft.SqlServer.Server and System.Web has been added.
Ah, it's System.Web.HttpContext.Current.Server.MapPath Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.