5

please tell me how to get image file size in bytes using javascript.

Thanks

Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
  • Please update your other (newly created) question. Please see this question for a nice snippet http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript/1310399#1310399. – alexn Dec 29 '10 at 07:51

3 Answers3

4

If you have a base64-encoded image src, you can use img.src.length * 0.75 to determine very close file size it will take if saved to disk.

avalanche1
  • 3,154
  • 1
  • 31
  • 38
4

If javascript engine supports canvas elements you can try to use canvas element and getImageData to fetch the pixel data from your image. Then, depending on type of the image you could create the binary representation of this image.

Here is info about canvas element and getImagedata api:

http://www.whatwg.org/specs/web-apps/current-work/#dom-context-2d-getimagedata

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
1

To get the image size, you need to access it on the server. Javascript is a client-side utility, so it can't directly retrieve information from a server.

You'd have to send an Ajax request to communicate with the server. Alternatively, when your page is created, save file sizes in <input type='hidden' /> boxes and access them when you need them, or a similar solution.

Ben
  • 54,723
  • 49
  • 178
  • 224
  • Javascript can read the image size and dimensions after loaded of course. img.scr = url; etc... – ruralcoder Jul 01 '12 at 00:16
  • 1
    @ruralcoder - dimensions yes, size no (see http://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript?lq=1); the question was about byte size. Also, it's `img.src`. – Ben Jul 02 '12 at 01:07