无法在javascript中获取图片的高度和宽度
我试图通过javascript来获取图片的实际高度和宽度。 在我的情况下使用的图像源是用户插入文件后立即生成的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);
下面是日志:
<img src="blob:http%3A//localhost%3A3000/af3e5a35-8c1c-40b5-ad5a-379c3ab1ec1d">
NEW IMAGE width 0
NEW IMAGE height: 0
斑是正确的,因为我可以在浏览器中查看图像。
当我用相同的blob在我的控制台中创建另一个图像并尝试检索高度和宽度时,一切正常。
但是,当我尝试在我的onChange事件表单中运行它时,输入信息的高度和宽度都是0。
尝试加载它首先:
img.onload(function() {
var w = img.width;
var h = img.height;
console.log("NEW IMAGE width", w);
console.log("NEW IMAGE height: ", h);
});
img.onload不是一个函数是我得到 –
需要采取的宽度和高度的形象得到了加载之后。所以需要花一些时间来加载图像。否则你会得到零大小总是。采取onload事件内的宽度/高度。
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);
}
它说“img.onload不是一个函数” –
你可以试试这个...它应该工作img.onload = function(){ var w = img.width; var h = img.height; console.log(“NEW IMAGE width”,w); console.log(“NEW IMAGE height:”,h); } – Nofi
在评论格式不好..我直接编辑我的帖子...请尝试,让我知道....请找到小提琴演示在“http://jsfiddle.net/Nofiden/vz844evq/ “...加载完整图片后,您将看到显示宽度和高度的警报。 – Nofi
如何获得blob对象中图像的高度和宽度? 例如:
$(function(){
\t $("input[name=file_name]").on('change',function(){
\t \t var url = window.URL || window.webkitURL || window.mozURL;
\t \t var src = url.createObjectURL($(this)[0].files[0]);
\t \t $("#box").html('<img src="'+src+'">');
\t \t $("#box img").attr('width','100');
\t \t $('img')[0].onload = function() {
\t \t console.log($(this).height()); //get image height by jQuery
\t \t console.log($(this)[0].height)// get image height by javascript
\t \t console.log($(this)[0].naturalHeight);//get real height by javascript
\t \t /**
\t \t * if you want to get the image's width,you can use following code :
\t \t * $(this).width();
\t \t * $(this)[0].width;
\t \t * $(this)[0].naturalWidth;
\t \t */
\t \t };
\t })
})
<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>
img.onload不是一个函数是我得到 –
请看演示屏幕截图我后来附着。 – jilykate