March 6, 2014

Get Height & Width of Uploaded Image

I have an FileUpload control that is used to upload images and now I need to check the dimensions (height, width) of the image from code behind. So, how can I go about that.

To solve this problem, I can use the System.Drawing.Image class and System.IO.Stream class to get height and width of the image. To do so, let’s add the FileUpload control on designer.

<asp:FileUpload ID="fu1" runat="server" />


Next, on the code-behind, I have a method that retrieves the uploaded file stream, loads an image from the stream and then obtains the dimension of the image. Note that I have skipped validation for the image on the FileUpload control and have assumed that a valid image is uploaded.

Code Snippet
  1. private string GetImageDimension()
  2. {
  3.     System.IO.Stream stream = fu1.PostedFile.InputStream;
  4.     System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
  6.     int height = image.Height;
  7.     int width = image.Width;
  9.     return "Height: " + height + "; Width: " + width;
  10. }


Reference: Shahed Kazi at