首先是canvas在线生成图片
html代码样式
<video id = "video" controls="controls" width = "250px" height ="150px" src = "/xiaogou.mp4">video> <div id="output">div> <input type="hidden" name="thumb" id = "thumb" value="">
js代码样式
(function(){ var video, output; var scale = 0.2 ; var initialize = function() { output = document.getElementById("output"); thumb = document.getElementById("thumb"); video = document.getElementById("video"); video.addEventListener('loadeddata',captureImage); }; var captureImage = function() { var canvas = document.createElement("canvas"); canvas.width = video.videoWidth * scale; canvas.height = video.videoHeight * scale; canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); var img = document.createElement("img"); img.src = canvas.toDataURL("image/png"); output.appendChild(img); thumb.value = canvas.toDataURL("image/png"); }; initialize(); })();
页面样式
此时图片路径已经保存在input隐藏域里面,form表单选择提交,接下来上后台PHP代码
用到以下方法
/** *功能:php完美实现下载远程图片保存到本地 *参数:文件url,保存文件目录,保存文件名称,使用的下载方式 *当保存文件名称为空时则使用远程文件原来的名称 */ function getImage($url, $save_dir = '', $filename = '', $type = 0) { if (trim($url) == '') { return array('file_name' => '', 'save_path' => '', 'error' => 1); } if (trim($save_dir) == '') { $save_dir = './'; } //创建保存目录 if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) { return array('file_name' => '', 'save_path' => '', 'error' => 5); } //获取远程文件所采用的方法 if ($type) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $img = curl_exec($ch); curl_close($ch); } else { ob_start(); readfile($url); $img = ob_get_contents(); ob_end_clean(); } //$size=strlen($img); //文件大小 $fp2 = @fopen($save_dir . $filename, 'a'); fwrite($fp2, $img); fclose($fp2); unset($img, $url); return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0); }在这边调用
//生成缩略图 $name = md5(time()); $thumb = I('request.thumb'); $time = date('Ymd'); $url = $this->getImage($thumb,'Uploads/thumb/'.$time.'/',$name.'.png'); //缩略图路径 $data['thumb'] = $url['save_path'];
文件保存在你设置的路径里,你也可以重命名,最后将服务器路径Insert进入数据库,搞定。
最后感谢这个文章
https://zhidao.baidu.com/question/2137906609475350508.html