3

I am trying to get the image dimensions of an image that user selects from list box. Image files are available on FTP server. I am displaying file names in a list box for users to select. Upon selection, I want to show the preview of image, for that I want to get dimensions so that I can resize it if i need to.

I am storing file name that is linked to currently selected list item into a string variable. I know that path on the server. I am using following code to create the Image object, but having no luck

try
{
     string dir = Session["currentUser"].ToString();
     System.Drawing.Image img = System.Drawing.Image.FromFile("~/Uploads/"+dir+"/"+fName, true);     //ERROR here, it gives me file URL as error message!
}
catch(Exception ex)
{
     lbl_Err.Text = ex.Message;
}

Not sure what is going wrong. Any ideas?

user1889838
  • 305
  • 4
  • 13
  • 35
  • So, what do you need? Do you get any exceptions, wrong values or don't you know how to get the values? – Andy Apr 09 '13 at 08:35
  • I'm not into asp.net, is something starting with ~ a valid path? – nvoigt Apr 09 '13 at 08:35
  • `FromFile` requires the `filename`, so I am giving a relative path (absolute path throws another error), but in exception it throws `System.IO.FileNotFoundException` and the message property of `ex` is `"~/Uploads/anemailtes/flower.png"` – user1889838 Apr 09 '13 at 08:41

1 Answers1

10

use Server.MapPath to fetch the image from the server.
As follows

System.Drawing.Image img = 
      System.Drawing.Image.FromFile(Server.MapPath("Uploads/"+dir+"/"+fName), true);  

You can use following as well

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

References
Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Community
  • 1
  • 1
शेखर
  • 16,910
  • 12
  • 52
  • 105
  • thanks, it worked. Could you explain, because it gave me error when i used server.mappath earlier (must be used in-correctly ) – user1889838 Apr 09 '13 at 08:44
  • Hi शेखर, How to get the image url in that From File method. For Ex: http://www.photos-public-domain.com/wp-content/uploads/2012/08/baby-blue-micro-fiber-cloth-fabric-texture.jpg – Vel May 21 '19 at 04:39
  • 1
    @Vel you need to use [web request](https://stackoverflow.com/questions/2368115/how-to-use-httpwebrequest-to-pull-image-from-website-to-local-file) – शेखर May 28 '19 at 04:56