Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client side Javascript get video width/height before upload

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!

like image 307
JasonAddFour Avatar asked Apr 08 '17 07:04

JasonAddFour


2 Answers

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>
like image 58
jasonify Avatar answered Sep 20 '22 22:09

jasonify


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);
});
like image 32
benoitz Avatar answered Sep 19 '22 22:09

benoitz