6

like:

<img src="http://www.google.com/intl/en_ALL/images/srpr/logo1w.png">

i want get logo1w.png file size 7.3kb

how to implement it?

Koerr
  • 15,215
  • 28
  • 78
  • 108

4 Answers4

3

You could do an HTTP HEAD request for the image URL. This will return the HTTP headers, which include the content-length (a.k.a. file size). This does require an additional request to the server, which is not very efficient when the image is generated instead of being served statically.

Manfre
  • 1,235
  • 10
  • 10
3

I don't know of any single way to consistently get the exact file size, but if you're willing to jump through some hoops, you could:

1) Estimate based on the dimensions and the file type. Because of compression techniques there's some wide variation, but you could probably run some statistics and come up with a half-decent heuristic.

2) In IE, use the fileSize property of an image. In other browsers that support Canvas, use the technique described in this question on getting image data in JavaScript to grab the dataURL, then do the math (multiply by 3/4, since base64 is a 4/3 size increase).

Edit

3) The suggestion others have given (particularly as elaborated in the question linked in Fabien Bernede's answer) about getting HTTP Headers is brilliant AND precise. Probably runs afoul of cross-domain restrictions in some cases, but still probably the most consistent and effective method.

Community
  • 1
  • 1
Weston C
  • 3,642
  • 2
  • 25
  • 31
  • 1
    surely the most 'consistent' and effective method is a server side proxy to grab the image and evaluate it! – redsquare Jul 17 '10 at 17:26
  • Totally correct, and worth noting to the asker -- I simply assumed they had some constraints or interest which meant they'd be doing this purely with JavaScript. – Weston C Jul 17 '10 at 17:46
2

You cannot in javascript (sorry even magical jQuery cannot help here!). You would need a server side script to fetch the image for you and calculate the size which you could return to your page.

Note - downvoters beware, the OP does not own the google domain!

redsquare
  • 78,161
  • 20
  • 151
  • 159
  • Any downloadable content has a size and there are a few well defined ways of retrieving that information. – Manfre Jul 18 '10 at 15:20
  • @user326404 not in js I am afraid – redsquare Jul 18 '10 at 18:54
  • 1
    @redsquare - That is incorrect. var xhr = new XMLHttpRequest(); xhr.open('HEAD', 'http://whatever.file.git', true); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length')); } } }; xhr.send(null); – bmelton Apr 12 '12 at 20:52
-4

$fileSize = strlen(file_get_contents($imageSrcTag)) // <-- php

GWolf
  • 1