【问题标题】:How to get image size from a path in javascript?如何从javascript中的路径获取图像大小?
【发布时间】:2019-12-28 13:09:30
【问题描述】:

我想用图片显示 div,它的名称、大小和 jquery 的下载链接。

为此,我制作了以下代码

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>

我的头像是

除图像大小外,一切正常@ 但在我的情况下,没有可用的文件[0],所以我怎样才能找到图像大小?

【问题讨论】:

标签: javascript jquery html image


【解决方案1】:

您可以使用fetch 来获取响应大小。由于您使用图像路径发出请求,因此响应大小将指向图像大小。

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">

获取图像宽度/高度的另一种方法是:使用Image 类:

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">

【讨论】:

  • 感谢您的回复,但正如我在代码中提到的那样,我正在动态制作图像 src,所以我该如何使用您的代码?
  • @MNJ 当然,只要有路径,就可以将其与fetchImage 一起使用。在这个例子中,我只是向你展示我们如何使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2021-03-21
相关资源
最近更新 更多