Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of an image without loading it, from a webserver

Tags:

c#

asp.net

image

Is it possible to get the size of an image (probably its size in bytes) from a web server, without loading it?

Do web servers have accessible properties (fields) with regard to file sizes? This would allow for checking the image size without loading.

Often when a web server's directory is loaded into a browser, it tells you each file's size, from server-side. Can I, as an ASP developer, access that data at all?

I'm using C# .Net 4

Edit: I am acting as a client and requesting this info from other web servers.

Appreciate any help, as always. Alex

like image 288
Alex Avatar asked Aug 17 '10 01:08

Alex


1 Answers

Do you mean when you are the server, or the client?

If you're the server, you can find it out whatever whay you could find it out about any other file (assuming the image stream is coming from a file).

new FileInfo(path).Length;

If you mean you're doing the client-code (you're accessing another webserver)

Do a HEAD request. While some servers don't behave correctly, the correct response to a HEAD is pretty much identical to that for a GET except that the entity isn't sent.

For example, to get the sprite PNG that is used on this page, the browser does a GET to http://sstatic.net/stackoverflow/img/sprites.png which results in the response:

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 Aug 2010 01:06:21 GMT
Content-Type: image/png
Connection: keep-alive
Cache-Control: max-age=604800
Last-Modified: Tue, 13 Jul 2010 06:28:14 GMT
Accept-Ranges: bytes
X-Powered-By: ASP.NET
Content-Length: 18607

followed by the octets of the actual image file.

Doing a HEAD instead of a get results in:

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 Aug 2010 01:07:20 GMT
Content-Type: image/png
Connection: keep-alive
Cache-Control: max-age=604800
Content-Length: 18607
Last-Modified: Tue, 13 Jul 2010 06:28:14 GMT
Accept-Ranges: bytes
X-Powered-By: ASP.NET

pretty much the same but without the entity body. At this point we can see that the image is 18607bytes in size, without actually downloading it. This method will not work though if the image would be sent chunked, as then the content-length would not be sent in a header.

Edit:

It's worth pointing out, that sometimes with chunked content you will have no choice but to download the whole thing, because the server will not say (and may not even know) the size when it starts sending. Sadly, this is likely to be use with particularly large streams too. Happily, this is unlikely to be used with images.

like image 60
Jon Hanna Avatar answered Oct 27 '22 19:10

Jon Hanna