首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法获得javascript中图像的高度和宽度

无法获得javascript中图像的高度和宽度
EN

Stack Overflow用户
提问于 2016-01-19 09:27:39
回答 4查看 21.1K关注 0票数 16

我试图通过javascript恢复图像的实际高度和宽度。在我的例子中使用的图像源是一个BLOB,只要用户插入一个文件,就会生成BLOB。

这是我的代码:

代码语言:javascript
运行
复制
    var img = document.createElement('img');
    var blob = URL.createObjectURL(e.target.files[0]);
    img.src = blob;
    console.log(img);
    var w = img.width;
    var h = img.height;
    console.log("NEW IMAGE width", w);
    console.log("NEW IMAGE height: ", h);

以下是日志:

代码语言:javascript
运行
复制
<img src=​"blob:​http%3A/​/​localhost%3A3000/​af3e5a35-8c1c-40b5-ad5a-379c3ab1ec1d">​
NEW IMAGE width 0
NEW IMAGE height:  0

blob是正确的,因为我可以在浏览器中查看图像。

当我在我的控制台中使用相同的blob创建另一个图像,并试图收回高度和宽度时,一切都运行得很好。

但是,当我试图在输入的onChange事件中那样运行它时,我只得到0的高度和宽度。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-01-19 09:35:41

加载图像后,您应该获得大小:

代码语言:javascript
运行
复制
    img.onload = getSize;//measure after loading or you will get 0

票数 19
EN

Stack Overflow用户

发布于 2016-01-19 09:37:49

需要获取图像加载后的宽度和高度。因此,需要给一些时间来加载image.Else,您将得到零大小的always.Take,即onload事件中的宽度/高度。

代码语言:javascript
运行
复制
var img = document.createElement('img');
    var blob = URL.createObjectURL(e.target.files[0]);
    img.src = blob;
    img.onload = function() {
      var w = img.width;
      var h = img.height;
      console.log("NEW IMAGE width", w);
      console.log("NEW IMAGE height: ", h);
    }
票数 14
EN

Stack Overflow用户

发布于 2017-09-01 03:57:07

如何在blob objeact中获取图像的高度和宽度?示例:

代码语言:javascript
运行
复制
$(function(){
	$("input[name=file_name]").on('change',function(){
		var url = window.URL || window.webkitURL || window.mozURL;
		var src = url.createObjectURL($(this)[0].files[0]);
		$("#box").html('<img src="'+src+'">');
		$("#box img").attr('width','100');
		$('img')[0].onload = function() {
		    console.log($(this).height()); //get image height by jQuery
		    console.log($(this)[0].height)// get image height by javascript
		    console.log($(this)[0].naturalHeight);//get real height by javascript
		    /**
		     * if you want to get the image's width,you can use following code :
		     * $(this).width();
		     * $(this)[0].width;
		     * $(this)[0].naturalWidth;
		     */
		};
	})
})
代码语言:javascript
运行
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" enctype="multipart/form-data">
  <input type="file" name="file_name">
</form>

<div id="box"></div>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34872975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档