我试图通过javascript恢复图像的实际高度和宽度。在我的例子中使用的图像源是一个BLOB,只要用户插入一个文件,就会生成BLOB。
这是我的代码:
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是正确的,因为我可以在浏览器中查看图像。
当我在我的控制台中使用相同的blob创建另一个图像,并试图收回高度和宽度时,一切都运行得很好。
但是,当我试图在输入的onChange事件中那样运行它时,我只得到0的高度和宽度。
发布于 2016-01-19 09:35:41
加载图像后,您应该获得大小:
img.onload = getSize;//measure after loading or you will get 0
发布于 2016-01-19 09:37:49
需要获取图像加载后的宽度和高度。因此,需要给一些时间来加载image.Else,您将得到零大小的always.Take,即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);
}
发布于 2017-09-01 03:57:07
如何在blob objeact中获取图像的高度和宽度?示例:
$(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;
*/
};
})
})
<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>
https://stackoverflow.com/questions/34872975
复制相似问题