Javascript client side gets the width / height of the video before loading

I am trying to combine a combination of HTML5 + FileReader API tags, but I did not understand how to get the sizes of the video that the user provides from their computer.

Here is what I refer to width / height:

HTML5 video sizes

<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 is possible to do this with a file from a user computer (which they selected using the usual html input tag).

Thank!

+4
source share
2 answers

A bit unclean solution using the base URL of FileReader + Data.

<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>
+4
source

You can set the height and width using the height and width property

<video controls>
<source src="Funny side up- Life of engineers_HIGH.mp4" type="video/mp4">
</video>
<script>
var video = document.getElementsByTagName("video")[0];
video.height = 300;
video.width = 700;
</script>
+1
source

Source: https://habr.com/ru/post/1674358/


All Articles