C# get width/height of image on web without downloading whole file?
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 absol开发者_JAVA技巧ute URI?
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.
I am a bit rusty at this, but with jpeg, it might not be as simple as it seems. Jpeg has a header within each segment of data which has its own height / width and resolution. jpeg was not designed to be streamed easily. You might need to read the entire image to find the width and height of each segment within the jpeg to get the entire width and height.
If you absolutely need to stream an image consider changing to another format which is easier to stream, jpeg is going to be tough.
You could do it if you can develop a server side program that would seek forward and read the header of each segment to compute the width and height of the segment.
It's a bit Heath Robinson, but since browsers seem to be able to do it perhaps you could automate IE to download the image within a webpage and then interrogate the browser's DOM to reveal the dimensions before the image has finished downloading?
Use this code:
public static async Task<Size> GetUrlImageSizeAsync(string url)
{
try
{
var request = WebRequest.Create(url);
request.Headers.Set(HttpRequestHeader.UserAgent, "Range: bytes=0-32");
var size = new Size();
using (var response = await request.GetResponseAsync())
{
var ms = new MemoryStream();
var stream = response.GetResponseStream();
stream.CopyTo(ms);
var img = Image.FromStream(ms);
size = img.Size;
}
return size;
}
catch
{
return new Size();
}
}
精彩评论