0

I saw this code to get the size(KB, MB) of an image. But this code is getting the data from the button after change. Can this code apply to my question?. Or is there any other way to directly get the size of the image using javascript?.

$(function () {
   $("#btnClick").change(function (e){
      var a = e.target.files[0];
      alert(parseFloat(a.size / 1024).toFixed(2) + " KB.");
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id ="btnClick"/>

EDIT As nnnnn said. I have an IMG (eg. < img src="someimg.jpg">) I want to get the size of this picture. How do I get it?. As my example above it store the size in the button and retrieve it.

KiRa
  • 924
  • 3
  • 17
  • 42
  • 1
    Can you more elaborate your question more please? It doesn't make sense at the moment. :) Do you want to show the size of an image already loaded to `` tag is it? – CodeMonkey May 08 '17 at 03:20
  • 1
    Are you saying you have `` and you want to get the size of *that* image's file? – nnnnnn May 08 '17 at 03:22
  • @nnnnnn yes you're exactly right. – KiRa May 08 '17 at 03:23
  • 2
    Perhaps you could [edit] your question to say that more clearly. I know it's in the question title, but say it in the question body before going off on a tangent about file inputs. It's confusing that the only HTML shown in the question doesn't include an ``. – nnnnnn May 08 '17 at 03:24
  • Cross origin issues may be able to resolve with [Cross-Origin XMLHttpRequest](https://developer.chrome.com/extensions/xhr or [HTTP access control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) – CodeMonkey May 08 '17 at 03:32
  • @Inuka I saw that yesterday and test it. But as I tested it I upload different size of image but it return the same result – KiRa May 08 '17 at 03:34

2 Answers2

6

There is no direct way from an <img> element to get any info on the data it has loaded, except to get its naturalWidth and naturalHeight values, and of course, if it is one of the valid Image types supported by the browser.

The only way then is to fetch the data again, as a Blob. From there, you'll be able to see the File's size. But note that this method is limited by the Same-Origin policies.

img.onload = e => {
  fetch(img.src).then(resp => resp.blob())
  .then(blob => {
    console.log(blob.size);
    });
  };
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/John_William_Waterhouse_A_Mermaid.jpg/800px-John_William_Waterhouse_A_Mermaid.jpg" id="img">
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • How do i use this code?. Do i need to put this inside a function?.. – KiRa May 08 '17 at 03:31
  • @KiRa, that's up to you. Here I am waiting for the image has loaded the resource so that the fetching uses the HTTP cache instead of making a new request to the server, but you can do as you wish. You could even first fetch this data, and set the ``'s `src` to `URL.createObjectURL(blob)`. – Kaiido May 08 '17 at 04:10
  • Took the liberty of demonstrating @Kaiido's answer in a fiddle here. Bare in mind this is not supported by the `Cross-Origin XMLHttpRequest` type. It needs to be allowed from the `server` side. for [Fiddle](https://jsfiddle.net/dsLL49rg/2/). see console for results. :) – CodeMonkey May 08 '17 at 04:14
  • @Kaiido I try to put inside a function but got an error – KiRa May 08 '17 at 05:04
  • @KiRa, does this error have a name or a small description ? Note that you are not forced to use the fetch API, you can also use XHR for older browsers, there is an `responseType = 'blob'` parameter. The code in this answer is only a broad proof of concept, you'll have to write your own version. But main idea is that you can not do it from an `` tag directly. – Kaiido May 08 '17 at 05:07
  • @Kaiido in the 1st - 3rd `=>` it says `Expected Expression` and in the `resp.blob())` `))` part is says `Expected ;` and lastly ` console.log(blob.size); });` the part ); -Expected Expression- – KiRa May 08 '17 at 05:10
  • The code block in my answer is in ES6, your browser doesn't support it. Here is an es5 version : https://jsfiddle.net/vzs55kkv/ – Kaiido May 08 '17 at 05:20
  • @Kaiido just want to ask.. What / Where does the img came from?. – KiRa May 08 '17 at 05:23
  • @KiRa, it's a bad shortcut for `getElementById('img')` don't use this hack in your code – Kaiido May 08 '17 at 05:25
  • @Kaiido even I use it I got an error :D. – KiRa May 08 '17 at 05:26
  • ... You mean directly in the fiddle or in your code ? You've seen the **bold** "*this method is limited by the Same-Origin policies.*" in the answer ? This means that this method won't work on external files, except if the external server is set up to accept external requests (which is not a default at all). – Kaiido May 08 '17 at 05:29
  • @Kaiido on my code :D btw thanks. I try to embed this to my code and find some other way. I hope I can do it. – KiRa May 08 '17 at 05:32
  • @Kaiido the result is in `KB` or `Bytes?` – KiRa May 08 '17 at 05:36
  • the result is in bytes, `blob` is almost exactly the same type of object as the one you get in your code from `e.target.files[0]` – Kaiido May 08 '17 at 05:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143650/discussion-between-kira-and-kaiido). – KiRa May 08 '17 at 05:53
1

You can use this function to get the file size of any file with passing the url :

function get_filesize(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("HEAD", url, true); // Notice "HEAD" instead of "GET",
                             //  to get only the header
    xhr.onreadystatechange = function() {
    if (this.readyState == this.DONE) {
        callback(parseInt(xhr.getResponseHeader("Content-Length")));
    }
};
    xhr.send();
}  

and Use it like this :

get_filesize("https://upload.wikimedia.org/wikipedia/commons/1/1e/Stonehenge.jpg", function(size) {
     alert("The size of image is: " + size + " bytes.");
});

Try it here : https://jsfiddle.net/emilvr/mv5r6xxm/

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
  • Instead of giving negative rate, go and do some research! this function return correct size! for files we have two different sizes : Size & Size on Disk. this function return the Size on Disk! Read more : http://www.fixedbyvonnie.com/2014/08/whats-difference-file-size-size-disk/#.WQ_rj1WGPIU – Emad Dehnavi May 08 '17 at 03:54
  • 1
    Your answer works perfectly well ! I don't know why that person downvoted you but I just upvoted your answer to correct his/her mistake. Have a good day ^^ – TheProgrammer Feb 19 '20 at 15:36