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">

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;
     canvas.width = cw;
     canvas.height = ch;
     var dataURL = canvas.toDataURL('image/png');

      type: 'POST',
      url: 'saveThumb.php',
      data: 'img=' + dataURL
    }).done(function(o) {
 }, false );
function draw(v,c,w,h) {

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

// 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 ? 🙂


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s