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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
<?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> |
requests.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?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(); } ?> |
Video
Â
NetBeans Project Download
Capture Image From Video NetBeans Project
Thanks friends
Your queries & suggestions are welcome in comments section
Please don’t forget to share if you find this helpful
Comments