動画からサムネイル画像を取得して保存する

Standard

JS:

<style>
  .space {
    height: 10px;
  }
  .timeline canvas {
    height: 100px;
  }
</style>
<div id="test">
 
</div>
<script>
  var videothumbs = function (cont, videosrc, typevideo) {
    var timeline = document.createElement('div'),
      video = document.createElement('video'),
      space = document.createElement('div'),
      time = 0,
      ended = false;
      count = 0;
 
    video.setAttribute('controls', 'controls');
    video.src = videosrc;
    video.type = typevideo;
 
    space.setAttribute('class', 'space');
    timeline.setAttribute('class', 'timeline');
    video.setAttribute('class', 'video');
 
    video.addEventListener('loadeddata', function (e) {
      loadTime();
    }, false);
    video.addEventListener('seeked', function () {
      if (ended === false) {
        createImage();
        loadTime();
      }
    }, false);
    video.addEventListener('ended', function (e) {
      ended = true;
    }, false);
 
    function loadTime() {
      if (ended === false) {
        time += (Math.ceil(video.duration / 9));
        if (time <= video.duration) {
          video.currentTime = time;
        } else {
          console.log('end');
          ended = true;
        }
      }
    };
    function createImage() {
      var canvas = document.createElement('canvas'),
 
      ctx = canvas.getContext('2d');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
      timeline.appendChild(canvas);
      var dataURL = canvas.toDataURL();
      saveImage(dataURL);
    };
    function saveImage(dataURL) {
      this.count++;
      $.ajax({
        url: "saveImage.php?count="+ this.count,
        data: {
          base64: dataURL
        },
        type: "post",
        complete: function () {
          console.log("Ok");
        }
      });
    }
 
    cont.appendChild(video);
    cont.appendChild(space);
    cont.appendChild(timeline);
    video.currentTime = 0;
  }
  videothumbs(document.getElementById('test'), './uploads/test.mp4', 'video/mp4');
</script>

PHP:

<?php
$baseFromJavascript = $_POST['base64'];
$base_to_php = explode(',', $baseFromJavascript);
$data = base64_decode($base_to_php[1]);
$filepath = "image_".$_GET['count'].".png";
file_put_contents($filepath,$data);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.