user12133523
user12133523

Reputation:

How to get image size from a path in javascript?

I want to show div with an image, it's name, it's size and it's download link with jquery.

for that, I have made below code

var image = 'image/example.png'
$('#download').attr("href", result2); 
$('.image').attr("src", result2); 
var name = result2.replace('image/', ''); 
$('.name').text(name);
$('.filename').css('display','block');
<div class="filename" style="display: none;">
    <img src="" class="image" width="100PX" height="100PX">
    <b class="name">example.png</b>             
    <span class="size"></span>
    <a href="" download="" id="download" class="btn" style="">DOWNLOAD</a>
</div>

and my image is

Image

everything is working fine except image size I don't know how can I get image size because when I was searching to get image size with it's MB, KB or in bytes with jquery it shows me a result in this formate $("#selector")[0].files[0].size but in my case, there is no files[0] is available so how can I find image size?

Upvotes: 0

Views: 1122

Answers (1)

T&#226;n
T&#226;n

Reputation: 1

You can use fetch to get the reponse size. Since you make a request with an image path, the response size will points to the image size.

fetch($('img').prop('src')).then(function (response) {
    console.log('size:', response.headers.get("content-length"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">

Another way to get the image width/height is: Using Image class:

var image = new Image();

image.onload = function () {
  console.log('width:', this.width);
  console.log('height:', this.height);
  
  console.log('more information about this image:');
  console.dir(this);
};

image.src = $('img').prop('src');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">

Upvotes: 2

Related Questions