Capture Image From Video and Saving to Server in Javascript Javascript Php by Rajesh Kumar Sahanee - July 14, 2020July 14, 20200 Post Views: 5,574 Hello Friends, Hope you are doing well. It’s being long time I haven’t share anything but today I am going to share how to capture image from video and saving to server in Javascript. Actually this requirement came to me because of a client’s mobile app where thumbnail image was required to show in the list of videos. There is two ajax request made to requests.php one to upload video and another to upload video thumbnail and finally there is submit button to submit the form. On submit of form I have only printed posted data you can use it according to your need i.e you can store it in database for further use. Let’s Code index.php index.php PHP <?php if (isset($_POST['save'])) { echo '<h3>Submitted Data - You Can Process According to Your Need</h3>'; echo '<pre>'; print_r($_POST); echo '</pre>'; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Capture Image From Video</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <style> #videouploadinput { width: 40px; height: 40px; position: absolute; top: -8px; right: 21px; z-index: -1; } #video { float: none; margin-top: 10px; min-height: 150px; border: solid thick aliceblue; } </style> </head> <body> <div class="container"> <div class="panel panel-default" style="margin-top: 5%"> <form action="" method="post"> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="name" class="control-label">Title *</label> <input type="text" class="form-control" name="title" id="title" placeholder="Video Title" required /> </div> </div> </div> <div class="row"> <div class="col-md-9"> <div class="form-group"> <label>Video (Click on upload icon to upload or link icon to fetch video from link)</label> <div class="pull-right"> <span id="uploadingspanmsg"></span> <label class="btn-flat btn btn-sm btn-default" title="Video Link" id="videoaddlink"><i class="fa fa-link"></i></label> <label class="btn-flat btn btn-sm btn-primary" title="Upload"><i class="fa fa-upload"></i><input id="videouploadinput" type="file" accept="video/*"></label> </div> <div class="" id="video" style="text-align: center;"> </div> <div style="text-align: center"> <a id="capturea" href="javascript:captureThumbnail()" style="display: none;">Capture Thumbnail</a> </div> </div> </div> <div class="col-md-3"> <input type="hidden" name="video_link_type" id="video_link_type"/> <input type="hidden" name="video_link" id="video_link"/> <input type="hidden" name="video_thumbnail" id="video_thumbnail"/> <div class="form-group"> <label class="control-label">Video Thumbnail</label> <img id="video_thumbnail_img" src="https://placehold.it/320x180" class="img-responsive"/> <input type="text" class="form-control" name="video_duration" id="video_duration" readonly=""/> </div> </div> </div> </div> <div class="panel-footer"> <input type="submit" class="btn btn-success" id="save" name="save" value="Save"/> </div> </form> </div> </div> <!-- REQUIRED JS SCRIPTS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $("#videouploadinput").change(function (e) { e.preventDefault(); var action = "requests.php?f=upload-video"; if ($("#videouploadinput").val() === "") { return; } $("#uploadingspanmsg").html("Uploading..."); var data = new FormData(); data.append("video", $('input[type=file]')[0].files[0]); $.ajax({ type: 'POST', url: action, data: data, /*THIS MUST BE DONE FOR FILE UPLOADING*/ contentType: false, processData: false, }).done(function (data) { $("#uploadingspanmsg").html(data.msg); if (data.code === '0') { $("#video_link_type").val("UPLOAD"); $("#video_link").val(data.file_url); $("#video").html('<video id="uploaded_video" controls><source src="' + data.file_url + '" type="video/mp4"></video>'); $("#save").attr("disabled", true); var vid = document.getElementById("uploaded_video"); vid.onloadedmetadata = function () { $("#save").attr("disabled", false); var seconds = document.getElementById("uploaded_video").duration; $("#video_duration").val(new Date(seconds * 1000).toISOString().substr(11, 8)); $("#capturea").show(); captureThumbnail(); }; } }).fail(function (data) { //any message }); }); $("#videoaddlink").click(function (e) { var videolink = window.prompt("Please paste image link here:", ""); if (videolink !== null && videolink !== "" && (videolink.startsWith("http://") || videolink.startsWith("https://"))) { $("#video_link_type").val("LINK"); $("#video_link").val(videolink); $("#video").html('<video id="uploaded_video" controls><source src="' + videolink + '" type="video/mp4"></video>'); $("#save").attr("disabled", true); var vid = document.getElementById("uploaded_video"); vid.onloadedmetadata = function () { $("#save").attr("disabled", false); var seconds = document.getElementById("uploaded_video").duration; $("#video_duration").val(new Date(seconds * 1000).toISOString().substr(11, 8)); $("#capturea").show(); captureThumbnail(); }; } }); function captureThumbnail() { var canvas = document.createElement('canvas'); var video = document.getElementById('uploaded_video'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); var imgsrc = canvas.toDataURL("image/png"); $("#video_thumbnail_img").attr("src", imgsrc); var dataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "requests.php?f=upload-video-thumbnail-base64", data: { imgBase64: dataURL } }).done(function (data) { if (data.code === '0') { $("#video_thumbnail").val(data.file_url); } }); } </script> </body> </html> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 <?phpif (isset($_POST['save'])) { echo '<h3>Submitted Data - You Can Process According to Your Need</h3>'; echo '<pre>'; print_r($_POST); echo '</pre>';}?><!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Capture Image From Video</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <style> #videouploadinput { width: 40px; height: 40px; position: absolute; top: -8px; right: 21px; z-index: -1; } #video { float: none; margin-top: 10px; min-height: 150px; border: solid thick aliceblue; } </style> </head> <body> <div class="container"> <div class="panel panel-default" style="margin-top: 5%"> <form action="" method="post"> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="name" class="control-label">Title *</label> <input type="text" class="form-control" name="title" id="title" placeholder="Video Title" required /> </div> </div> </div> <div class="row"> <div class="col-md-9"> <div class="form-group"> <label>Video (Click on upload icon to upload or link icon to fetch video from link)</label> <div class="pull-right"> <span id="uploadingspanmsg"></span> <label class="btn-flat btn btn-sm btn-default" title="Video Link" id="videoaddlink"><i class="fa fa-link"></i></label> <label class="btn-flat btn btn-sm btn-primary" title="Upload"><i class="fa fa-upload"></i><input id="videouploadinput" type="file" accept="video/*"></label> </div> <div class="" id="video" style="text-align: center;"> </div> <div style="text-align: center"> <a id="capturea" href="javascript:captureThumbnail()" style="display: none;">Capture Thumbnail</a> </div> </div> </div> <div class="col-md-3"> <input type="hidden" name="video_link_type" id="video_link_type"/> <input type="hidden" name="video_link" id="video_link"/> <input type="hidden" name="video_thumbnail" id="video_thumbnail"/> <div class="form-group"> <label class="control-label">Video Thumbnail</label> <img id="video_thumbnail_img" src="https://placehold.it/320x180" class="img-responsive"/> <input type="text" class="form-control" name="video_duration" id="video_duration" readonly=""/> </div> </div> </div> </div> <div class="panel-footer"> <input type="submit" class="btn btn-success" id="save" name="save" value="Save"/> </div> </form> </div> </div> <!-- REQUIRED JS SCRIPTS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $("#videouploadinput").change(function (e) { e.preventDefault(); var action = "requests.php?f=upload-video"; if ($("#videouploadinput").val() === "") { return; } $("#uploadingspanmsg").html("Uploading..."); var data = new FormData(); data.append("video", $('input[type=file]')[0].files[0]); $.ajax({ type: 'POST', url: action, data: data, /*THIS MUST BE DONE FOR FILE UPLOADING*/ contentType: false, processData: false, }).done(function (data) { $("#uploadingspanmsg").html(data.msg); if (data.code === '0') { $("#video_link_type").val("UPLOAD"); $("#video_link").val(data.file_url); $("#video").html('<video id="uploaded_video" controls><source src="' + data.file_url + '" type="video/mp4"></video>'); $("#save").attr("disabled", true); var vid = document.getElementById("uploaded_video"); vid.onloadedmetadata = function () { $("#save").attr("disabled", false); var seconds = document.getElementById("uploaded_video").duration; $("#video_duration").val(new Date(seconds * 1000).toISOString().substr(11, 8)); $("#capturea").show(); captureThumbnail(); }; } }).fail(function (data) { //any message }); }); $("#videoaddlink").click(function (e) { var videolink = window.prompt("Please paste image link here:", ""); if (videolink !== null && videolink !== "" && (videolink.startsWith("http://") || videolink.startsWith("https://"))) { $("#video_link_type").val("LINK"); $("#video_link").val(videolink); $("#video").html('<video id="uploaded_video" controls><source src="' + videolink + '" type="video/mp4"></video>'); $("#save").attr("disabled", true); var vid = document.getElementById("uploaded_video"); vid.onloadedmetadata = function () { $("#save").attr("disabled", false); var seconds = document.getElementById("uploaded_video").duration; $("#video_duration").val(new Date(seconds * 1000).toISOString().substr(11, 8)); $("#capturea").show(); captureThumbnail(); }; } }); function captureThumbnail() { var canvas = document.createElement('canvas'); var video = document.getElementById('uploaded_video'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); var imgsrc = canvas.toDataURL("image/png"); $("#video_thumbnail_img").attr("src", imgsrc); var dataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "requests.php?f=upload-video-thumbnail-base64", data: { imgBase64: dataURL } }).done(function (data) { if (data.code === '0') { $("#video_thumbnail").val(data.file_url); } }); } </script> </body></html> requests.php requests.php PHP <?php define('ERROR_RESPOSE_CODE', '1'); define('SUCCESS_RESPOSE_CODE', '0'); if (isset($_REQUEST['f']) && trim($_REQUEST['f']) == 'upload-video') { $response = array('code' => ERROR_RESPOSE_CODE, 'msg' => "Error"); $upload_path = 'uploads/videos/'; if (!file_exists($upload_path)) { mkdir($upload_path, 0777, true); } $upload_url = $upload_path; if ($_SERVER['REQUEST_METHOD'] == 'POST') { //checking the required parameters from the request if (isset($_FILES['video']['name'])) { $fileinfo = pathinfo($_FILES['video']['name']); $extension = $fileinfo['extension']; $filename = 'video_' . date('d') . '_' . md5(time()); $file_url = $upload_url . $filename . '.' . $extension; //file path to upload in the server $file_path = $upload_path . $filename . '.' . $extension; try { //saving the file if (move_uploaded_file($_FILES['video']['tmp_name'], $file_path)) { $response['code'] = SUCCESS_RESPOSE_CODE; $response['file_url'] = $file_url; $response['msg'] = 'Uploaded successfully!'; $response['htmlmsg'] = '<div class="alert alert-success">Uploaded successfully!</div>'; } } catch (Exception $e) { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Error!'; $response['htmlmsg'] = '<div class="alert alert-danger">Error!</div>'; } } else { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Please choose file!'; $response['htmlmsg'] = '<div class="alert alert-danger">Please choose file!</div>'; } } header("Content-Type:application/json"); echo json_encode($response); exit(); } if (isset($_REQUEST['f']) && trim($_REQUEST['f']) == 'upload-video-thumbnail-base64') { $response = array('code' => ERROR_RESPOSE_CODE, 'msg' => "Error"); $upload_path = 'uploads/video-thumbnails/'; if (!file_exists($upload_path)) { mkdir($upload_path, 0777, true); } $upload_url = $upload_path; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $filename = 'thumbnail_' . date('d') . '_' . md5(time()); $file_url = $upload_url . $filename . '.png'; //file path to upload in the server $file_path = $upload_path . $filename . '.png'; //saving the file $img = $_POST['imgBase64']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $success = file_put_contents($file_path, $data); if ($success) { $response['code'] = SUCCESS_RESPOSE_CODE; $response['file_url'] = $file_url; $response['msg'] = 'Uploaded successfully!'; $response['htmlmsg'] = '<div class="alert alert-success">Uploaded successfully!</div>'; } else { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Error!'; $response['htmlmsg'] = '<div class="alert alert-danger">Error!</div>'; } } header("Content-Type:application/json"); echo json_encode($response); exit(); } ?> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 <?phpdefine('ERROR_RESPOSE_CODE', '1');define('SUCCESS_RESPOSE_CODE', '0'); if (isset($_REQUEST['f']) && trim($_REQUEST['f']) == 'upload-video') { $response = array('code' => ERROR_RESPOSE_CODE, 'msg' => "Error"); $upload_path = 'uploads/videos/'; if (!file_exists($upload_path)) { mkdir($upload_path, 0777, true); } $upload_url = $upload_path; if ($_SERVER['REQUEST_METHOD'] == 'POST') { //checking the required parameters from the request if (isset($_FILES['video']['name'])) { $fileinfo = pathinfo($_FILES['video']['name']); $extension = $fileinfo['extension']; $filename = 'video_' . date('d') . '_' . md5(time()); $file_url = $upload_url . $filename . '.' . $extension; //file path to upload in the server $file_path = $upload_path . $filename . '.' . $extension; try { //saving the file if (move_uploaded_file($_FILES['video']['tmp_name'], $file_path)) { $response['code'] = SUCCESS_RESPOSE_CODE; $response['file_url'] = $file_url; $response['msg'] = 'Uploaded successfully!'; $response['htmlmsg'] = '<div class="alert alert-success">Uploaded successfully!</div>'; } } catch (Exception $e) { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Error!'; $response['htmlmsg'] = '<div class="alert alert-danger">Error!</div>'; } } else { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Please choose file!'; $response['htmlmsg'] = '<div class="alert alert-danger">Please choose file!</div>'; } } header("Content-Type:application/json"); echo json_encode($response); exit();} if (isset($_REQUEST['f']) && trim($_REQUEST['f']) == 'upload-video-thumbnail-base64') { $response = array('code' => ERROR_RESPOSE_CODE, 'msg' => "Error"); $upload_path = 'uploads/video-thumbnails/'; if (!file_exists($upload_path)) { mkdir($upload_path, 0777, true); } $upload_url = $upload_path; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $filename = 'thumbnail_' . date('d') . '_' . md5(time()); $file_url = $upload_url . $filename . '.png'; //file path to upload in the server $file_path = $upload_path . $filename . '.png'; //saving the file $img = $_POST['imgBase64']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $success = file_put_contents($file_path, $data); if ($success) { $response['code'] = SUCCESS_RESPOSE_CODE; $response['file_url'] = $file_url; $response['msg'] = 'Uploaded successfully!'; $response['htmlmsg'] = '<div class="alert alert-success">Uploaded successfully!</div>'; } else { $response['code'] = ERROR_RESPOSE_CODE; $response['msg'] = 'Error!'; $response['htmlmsg'] = '<div class="alert alert-danger">Error!</div>'; } } header("Content-Type:application/json"); echo json_encode($response); exit();}?> Video https://zatackcoder.com/wp-content/uploads/2020/07/capture-image-from-video.mp4 NetBeans Project Download Capture Image From Video NetBeans Project 1 file(s) 1.20 MB Download Thanks friendsYour queries & suggestions are welcome in comments sectionPlease don’t forget to share if you find this helpful