C# get width/height of image on web without downloading whole file?
.net, c#, console, windows
Solution
First, you can request the first hundred bytes of an image using the Range header.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Set(HttpRequestHeader.UserAgent, "Range: bytes=0-100");
Next, you need to decode. The unix `file` command has a table of common formats, and the locations of key information. I'd suggest installing Cygwin and taking a look at `/usr/share/file/magic`.
For `gif`'s and `png`'s, you can easily get the image dimensions from the first 32 bytes. However, for JPEGs, @Andrew is correct in that you can't reliably get this information. You can figure out if it has a thumbnail, and the size of the thumbnail.
The get the actual jpeg size, you need to scan for the `start of frame` tag. Unfortunately, one can't reliably determine where this is going to be in advance, and a thumbnail could push it several thousand bytes into the file.
I'd recommend using the `range` request to get the first 32 bytes. This will let you determine the file type. After which, if it's a JPEG, then download the whole file, and use a library to get the size information.
Problem
I believe with JPGs, the width and height information is stored within the first few bytes. What's the easiest way to get this information given an absolute URI?