In this article I will explain how to get (find) the File Size in KB, Dimensions i.e. Height and Width of uploaded Image in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of a FileUpload control and a Button.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" />
Determining File Size, Dimensions (Height and Width) of Uploaded Image in ASP.Net
When the Button is clicked, the following event handler is executed. Here first the uploaded Image file is read into an Image object and its dimensions i.e. Height and Width are determined.
Then using the ContentLength property of the PostedFile, the size of the File is calculated in Kilobytes (KB).
Finally the File Size in KB, the Height and Width are displayed using JavaScript alert message box.
C#
protected void Upload(object sender, EventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
int height = img.Height;
int width = img.Width;
decimal size = Math.Round(((decimal)FileUpload1.PostedFile.ContentLength / (decimal)1024), 2);
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Size: " + size + "KB\\nHeight: " + height + "\\nWidth: " + width + "');", true);
}
VB.Net
Protected Sub Upload(sender As Object, e As EventArgs)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Dim height As Integer = img.Height
Dim width As Integer = img.Width
Dim size As Decimal = Math.Round((CDec(FileUpload1.PostedFile.ContentLength) / CDec(1024)), 2)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Size: " & size.ToString() & "KB\nHeight: " & height.ToString() + "\nWidth: " & width.ToString() & "');", True)
End Sub
Screenshot
Demo
Downloads