I've been trying to piece together a combination of HTML5 video tag + the FileReader API but I haven't figured out how to get the dimensions of a video that a user is providing from their own computer.
Here is what I am referencing for width/ height:
HTML5 Video Dimensions
<video id="foo" src="foo.mp4"></video>
var vid = document.getElementById("foo");
vid.videoHeight; // returns the intrinsic height of the video
vid.videoWidth; // returns the intrinsic width of the video
But I want to know if it's possible to do this with a file from a user's computer (that they have selected via a normal input html tag).
Thanks!
A bit unclean solution using basic FileReader + Data URL.
<html>
<head>
<style>
div {
margin: 20px;
}
</style>
</head>
<body>
<h1>Get Dimensions</h1>
<div>
<label for="load-file">Load a file:</label>
<input type="file" id="load-file">
</div>
<div>
<button type="button" id="done-button">Get me dimensions</button>
</div>
<script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
<script>
(function ($) {
$('#done-button').on('click', function () {
var file = $('#load-file')[0].files[0];
var reader = new FileReader();
var fileType = file.type;
console.log("type", fileType);
reader.addEventListener("load", function () {
var dataUrl = reader.result;
var videoId = "videoMain";
var $videoEl = $('<video id="' + videoId + '"></video>');
$("body").append($videoEl);
$videoEl.attr('src', dataUrl);
var videoTagRef = $videoEl[0];
videoTagRef.addEventListener('loadedmetadata', function(e){
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
})(jQuery);
</script>
</body>
</html>
Here is a simple and fast solution to get a video's size before upload. It doesn't require any dependency.
const url = URL.createObjectURL(file);
const $video = document.createElement("video");
$video.src = url;
$video.addEventListener("loadedmetadata", function () {
console.log("width:", this.videoWidth);
console.log("height:", this.videoHeight);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With