C # get image width / height on the Internet without downloading the whole file?

I believe that with JPG, width and height information is stored within the first few bytes . What is the easiest way to get this information with an absolute URI?

+4
source share
3 answers

First, you can request the first hundreds of bytes of the image using the Range header.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Headers.Set(HttpRequestHeader.UserAgent, "Range: bytes=0-100"); 

Then you need to decode. The unix file command contains a table of common formats and the location of key information. I would suggest installing Cygwin and taking a look at /usr/share/file/magic .

For gif and png you can easily get image sizes from the first 32 bytes. However, for JPEG files, @Andrew is correct that you cannot reliably obtain this information. You can determine if there is a thumbnail and the size of the thumbnail.

Get the actual jpeg size, you need to scan the start of frame tag. Unfortunately, you cannot reliably determine where this will happen in advance, and a sketch can push it to several thousand bytes.

I would recommend using a range query to get the first 32 bytes. This will allow you to determine the type of file. Then, if it's JPEG, then download the entire file and use the library to get size information.

+7
source

I'm a little rusty, but with jpeg it might not be as easy as it sounds. Jpeg has a header in each data segment, which has its own height / width and resolution. jpeg is not intended for streaming. You may need to read the entire image to find the width and height of each segment in jpeg to get the whole width and height.

If you absolutely need to transfer the image by switching to another format that is easier to transfer, jpeg will be tough.

This can be done if you can develop a server program that will look forward and read the header of each segment to calculate the width and height of the segment.

+2
source

A bit of Heath Robinson , but since browsers seem to be able to do this, maybe you can automate IE to load an image within a web page and then poll the browser DOM to show the dimensions before the image finishes loading?

0
source

All Articles