Get file size and dimensions of an Image from the Web in C#

The 1st method can be used for any kind of file.

public static int GetFileSize(string fileUrl)
{
    var request = System.Net.HttpWebRequest.Create(fileUrl);

    request.Method = "HEAD";

    using (var response = request.GetResponse())
    {
        int contentLength = 0;
        int.TryParse(response.Headers.Get("Content-Length"),
                out contentLength);

        return contentLength;
    }
}

public static System.Drawing.Size GetSize(string imageUrl)
{
    var request = System.Net.WebRequest.Create(imageUrl);

    request.Method = "GET";
    request.Accept = "image/jpeg";

    using (var response = (System.Net.HttpWebResponse)request.GetResponse())
    {
        using (var s = response.GetResponseStream())
        {
            var bmp = new System.Drawing.Bitmap(s);
            var size = new System.Drawing.Size(bmp.Width, bmp.Height);
                    
            return size;
        }
    }

}

public static int GetWidth(string imageUrl)
{
    return GetSize(imageUrl).Width;
}

public static int GetHeight(string imageUrl)
{
    return GetSize(imageUrl).Height;
}

picture | dimension | get file size | back-end | code-behind | ajax

Advertisements

3 thoughts on “Get file size and dimensions of an Image from the Web in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s