Determining image file size + dimensions via Javascript?

后端 未结 11 1088
执念已碎
执念已碎 2020-11-22 07:00

As part of a web app, once images have been downloaded and rendered on a web page, I need to determine an image\'s file size (kb) and resolution within the browser context (

相关标签:
11条回答
  • 2020-11-22 07:45

    How about this:

    var imageUrl = 'https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg';
    var blob = null;
    var xhr = new XMLHttpRequest(); 
    xhr.open('GET', imageUrl, true); 
    xhr.responseType = 'blob';
    xhr.onload = function() 
    {
        blob = xhr.response;
        console.log(blob, blob.size);
    }
    xhr.send();
    

    http://qnimate.com/javascript-create-file-object-from-url/

    due to Same Origin Policy, only work under same origin

    0 讨论(0)
  • 2020-11-22 07:51

    You can find dimension of an image on the page using something like

    document.getElementById('someImage').width
    

    file size, however, you will have to use something server-side

    0 讨论(0)
  • 2020-11-22 07:54

    Regarding the width and height:

    var img = document.getElementById('imageId'); 
    
    var width = img.clientWidth;
    var height = img.clientHeight;
    

    Regarding the filesize you can use performance

    var size = performance.getEntriesByName(url)[0];
    console.log(size.transferSize); // or decodedBodySize might differ if compression is used on server side
    
    0 讨论(0)
  • 2020-11-22 07:59

    Check the uploaded image size using Javascript

    <script type="text/javascript">
        function check(){
          var imgpath=document.getElementById('imgfile');
          if (!imgpath.value==""){
            var img=imgpath.files[0].size;
            var imgsize=img/1024; 
            alert(imgsize);
          }
        }
    </script>
    

    Html code

    <form method="post" enctype="multipart/form-data" onsubmit="return check();">
    <input type="file" name="imgfile" id="imgfile"><br><input type="submit">
    </form>
    
    0 讨论(0)
  • 2020-11-22 07:59

    You can get the dimensions using getElement(...).width and ...height.

    Since JavaScript can't access anything on the local disk for security reasons, you can't examine local files. This is also true for files in the browser's cache.

    You really need a server which can process AJAX requests. On that server, install a service that downloads the image and saves the data stream in a dummy output which just counts the bytes. Note that you can't always rely on the Content-length header field since the image data might be encoded. Otherwise, it would be enough to send a HTTP HEAD request.

    0 讨论(0)
提交回复
热议问题