Search code examples
c#.netvariablesfileinfo

Image sizes in a FileInfo variable


I'm currently working on a control which displays all images held within a folder so that the client is aware of what they have uploaded.

I have set attributes I wish to display, in order to keep them informed on what they have uploaded. So far everything is going well but I have come across a small problem.

What I would like to do is display the height and width of the uploaded images, but I currently can't find a way of doing this. Can anyone point me in the right direction??

So far my code looks like this:

FileInfo[] files = new DirectoryInfo(Server.MapPath(@"..\_includes\images\uploads\") + folder).GetFiles();

var imagefiles = from FileInfo f in files
                         where f.Exists
                         select new
                         {
                             url = imageurl + f.Name,
                             name = f.Name,
                             creation = f.CreationTime.ToLongDateString(),
                             filesize = (f.Length / 1024).ToString() + "KB",
                         };

Solution

  • You need to load the image into an Image object - this will give you the dimensions of the image.

    using(var img = Image.FromFile(file.Name))
    {
      var height = img.Height;
      var width = img.Width;
    }