I'm having issues reading sizes with file reader. Have tried various browsers and files, width always comes back as 0.
var fileReader = new FileReader();
var img = new Image();
fileReader.onload = function(event) {
img.src = event.target.result;
console.log(img.width);
};
fileReader.onerror = function() {
//handle error
};
fileReader.readAsDataURL(file);
The file var is looped out from the following on a drag and drop event:
e.originalEvent.dataTransfer.files
也许您的图片对象未加载,请尝试以下操作:
img.onload = function () {console.log(img.width)}
I think you have an error while assigning binary data to Image.
Assigning image:
fileReader.onload = function(e) {
var img = new Image();
img.src = fileReader.result;
}
Demo:
document.getElementById('img').addEventListener('change', function(e) { var file = this.files[0]; var fileReader = new FileReader(); var img = new Image(); fileReader.onload = function(event) { img.src = fileReader.result; img.onload = function() { console.log(img.width); } document.getElementById('result').appendChild(img); }; fileReader.readAsDataURL(file); })
<input id="img" type="file"> <div id="result"></div>
see codepen demo or jsfiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.