Saving a canvas to a PNG or JPEG file

I’m currently programming a webstie where the users can Upload .mp4 videos. I would like to make a thumbnail when the user uploads his video and write this image to a .jpg or .png file on my server.

The problem that I encounter is that the file is stored on my server but it isn’t viewed/ seen as an image file.

This is my code for the moment.

The HTML part

<canvas id="c"></canvas>
<video id="v" controls>
  <source src="/215003/1.1/videos/7/f9ed57e2b0ee1e87a4cbc17c7b743eff.mp4" type="video/mp4">
</video>
https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js

The javascript part where I process the canvas etc.

document.addEventListener('DOMContentLoaded', function(){
var v = document.getElementById('v');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');

var v = document.getElementById("v");

v.addEventListener('canplay', function() {
 this.currentTime = this.duration / 2;
  }, false);

v.addEventListener( "loadedmetadata", function (e) {
 var cw = this.videoWidth,
     ch = this.videoHeight;
     console.log(cw);
     console.log(ch);
     canvas.width = cw;
     canvas.height = ch;
     draw(this,context,cw,ch);
     var dataURL = canvas.toDataURL('image/png');

    $.ajax({
      type: 'POST',
      url: 'saveThumb.php',
      data: 'img=' + dataURL
    }).done(function(o) {
        console.log(dataURL);
      console.log('saved'); 
    });
 }, false );
},false);
function draw(v,c,w,h) {
  c.drawImage(v,0,0,w,h);
  setTimeout(draw,20,v,c,w,h);
}

The PHP file to process the data and store the image :

<?php
// requires php5
define('UPLOAD_DIR', 'img/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

Somebody that can help me out ? 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s