2016-11-04 5 views
1

저는 초보자이며 PHP에서 비디오 파일의 미리보기 이미지를 얻는 방법을 모르겠습니다. 나를 도울 구체적인 해결책을 찾지 못했습니다. 나는 ffmpeg 라이브러리를 시도했다. 하지만 지금은 ffmpeg thumbnail.so없이 도와주세요. 이것은 내 codeigniter 코드입니다. 검토하시기 바랍니다.ffmpeg없이 비디오 파일의 미리보기 이미지를 얻고 저장하는 방법은 무엇입니까?

<?php 
$extension = pathinfo($_FILES["url"]["name"], PATHINFO_EXTENSION);/* Get file extension */ 
$filename = time() . '_' . mt_rand() . '.' . $extension; 
move_uploaded_file($_FILES['url']['tmp_name'], $destinationPath . $filename); 
$params['filename'] =$destinationPath.$filename; 

$params['thumbImageName'] =$destinationPath.$thumbImageName; 



     $this->load->library('resize',$params); 
     $this->resize->resizeImage(WEIGHT, HEIGHT); 
     $this->resize->saveImage($destinationPath.$thumbImageName, 100); 
?> 
+0

ffmpeg가 필요합니다. ffmpeg와 같은 도구가 없으면 불가능합니다. –

+0

사용자에게 업로드를 요청 ... –

답변

1

실제로 방법이 있습니다.

방법 : 사용자가 업로드 할 비디오를 선택합니다. 선택 후, 팝업 div에서 로딩 메시지를 표시하거나 경고 상자를 사용하십시오. 그런 다음 비디오 파일을 비디오 태그에로드하십시오. 비디오 태그를 표시하는 것이 가장 좋습니다 : 없음. 동영상 태그가 준비 상태가되면 동영상의 50 %로 건너 뜁니다. 그런 다음 동영상 태그의 스크린 샷을 가져옵니다. 이미지를 base64로 가져온 다음 비디오와 함께 Ajax를 통해 PHP로 전송할 수 있습니다.

(메도 :... 취소 utilisateur sélectionne 라 비디오 à téléverser 즐긴 드 sélectionner, montrez 않은 메시지 드 chargement, 적합 UNE 인 Fenetre ou는 utiliser 단한 BOITE 디부 레르 Puis, 충전기 라 비디오 비디오 드 요소 않은 à 셀라의 MIEUX 이미지는 50 %로 표시됩니다. Puis, prenez une capture d' écran d'élément vidéo. alors envoyez-la à PHP avec Ajax)

base64 스크립트에 대한 입력 태그를 포함하십시오. (Incluez 않은 요소 디부 연예 르 스크립트 64 기수를 붓는다.)

<html> 
<form action="" method="post" enctype="multipart/form-data" id="uploadvidform" accept="video/*"> 
    <input type="file" name="file" id="file" /> 
    <input type="text" name="screenshotbase64" id="screenshotbase64" value="" style="display: none;" /> 
</form> 
<input type="button" value="Upload" id="uploadvidbut" /> 

그리고 보이지 않는 비디오 요소를. (ET 난 요소 드 비디오 보이지 않는.)

<video width="400" id="videoelem" style="display: none;" controls> 
    <source src="" id="video_src"> 
    Your browser does not support HTML5 video. 
</video> 

그리고 스크립트. 먼저, 파일이 선택되었을 때 작업을 수행하십시오. 헤드 요소에 Google Ajax 파일을 연결했는지 확인하십시오.

<script> 
var scalefac = 0.25; 
// Scale of image; 
// Echelle de l'image; 
var screenshots = []; 
// An array for multiple screenshots; 
// Un tableau pour plusieurs captures d'écran; 

// This function will create an image. It's not used now, it's used in the below action (when you change the file). 
// Cette fonctionne créera une image. C'est pas pour maintenant c'est pour la fonctionne suivante (lorsqu'on change le fichier). 
function capture(video, scalefac) { 
    if(scaleFactor == null){ 
     scaleFactor = 1; 
    } 
    var w = video.videoWidth * scalefac; 
    var h = video.videoHeight * scalefac; 
    var canvas = document.createElement('canvas'); 
     canvas.width = w; 
     canvas.height = h; 
    var ctx = canvas.getContext('2d'); 
     ctx.drawImage(video, 0, 0, w, h); 
    return canvas; 
} 

$(document).ready(function(){ 

$(document).on("change", "#file", function(){ 
    alert("Please wait while we verify your video. This will only take a couple of seconds."); 
    // The next 3 lines will load the video 
    // Les 3 lignes suivantes chargeront la vidéo 
    var lasource = $('#video_src'); 
    lasource[0].src = URL.createObjectURL($('#file').prop("files")[0]); 
    lasource.parent()[0].load(); 
    var video = document.getElementById("videoelem"); 
    setTimeout(function(){ 
     // Video needs to load then we check the state. 
     // Il faut que la vidéo charge puis nous vérifier l'état. 
     if (video.readyState == "4"){ 
      var videoduration = $("#videoelem").get(0).duration; 
      var timetogoto = videodurationinseconds/2; 
      $("#videoelem").get(0).currentTime = timetogoto; 
      setTimeout(function(){ 
       // Video needs to load again 
       // Il faut que la vidéo charge de nouveau 
       var video = document.getElementById("videoelem"); 
       // function the screen grab. 
       // fonctionne la capture d'écan. 
       var canvas = capture(video, scalefac); 
       screenshots.unshift(canvas); 
       for(var i=0; i<4; i++){ 
        $("#screenshotbase64").val(screenshots[i].toDataURL()); 
       } 
      }, 500); 
    }, 3000);  
}); 

// Now that the form is filled, you can send your data to your PHP file. 
// Maintenant que le formulaire est rempli vous pouvez envoyer les données à votre fichier de PHP. 

$(document).on('click', '#uploadvidbut', function(){ 
    var form = new FormData($("#uploadvidform")[0]); 
    $.ajax({ 
     url: '/uploadvideodocument.php', // PHP file - Fichier de PHP 
     type: 'POST', 
     data: form,     
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (result){ 
      if (result == 1){ 
       alert("The video has been uploaded."); 
      } 
     } 
    }).fail(function(){ 
     alert("Oh no, the video wasn't uploaded."); 
    }); 
}); 

}); 
</script> 

그리고 이제 PHP (디부 abord, UNE 조치는 lorsqu'on sélecionne 르 fichier. Assurez 있니 디부 avoir 거짓말 르 fichier 드 구글 아약스, 적합 난 요소는 단. 부어 faites) 파일. base64 변환을 이미지에만 포함 할 예정입니다. 나머지 작업을 수행하는 방법을 알고 싶습니다.

(. 잇 maintenant 르 fichier PHP 이인제 가지요 seulement inclure 라 변환 base64로, 적합의 UNE 이미지, j'espère 가야 있니 savez 의견을 방임 르 reste.)

<?php 

    $data = $_POST['screenshotbase64']; 
    list($type, $data) = explode(';', $data); 
    list(, $data) = explode(',', $data); 
    $data = base64_decode($data); 
    // The following 2 lines will create the time in microseconds which you can use as the name. Microseconds ensures an almost impossibility of two people uploading at the same time. 
    // Les 2 lignes suivantes créeront les temps dans microseconds, vous pouvez l'utiliser en tant que le nom. Utiliser les microseconds garantira une presque impossibilité de noms en double. 
    $mt = explode(' ', microtime()); 
    $millies = ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000)); 
    $screenshotfilename = time(). $millies . '.png'; 
    // In the next line, replace YOUR DIRECTORY with your home path and then include the folder of where you want to save the screenshot. 
    // Dans la ligne suivante, remplacez YOUR DIRECTORY par votre chemin d'accès, puis incluez le dossier dans lequel vous souhaitez sauvegarder la capture. 
    file_put_contents('YOUR DIRECTORY AND FOLDER' . $screenshotfilename, $data); 

    // Now, the screen shot has been saved to the server and the name of the file is $screenshotfilename. 
    // Maintenant la capure d'écran a été sauvegardée à votre serveur et le nom du fichier est $screenshotfilename. 

?> 

마십시오 :

일부 브라우저는 동영상 요소를 허용하지 않을 수 있습니다. 요즘은 거의 발생하지 않습니다. 그러나 그런 것을 명심하십시오.

Veuillez의 재치 :

Certains navigateurs peuvent 네브라스카 싶어서 수납기 난 요소 비디오. Mais de nos jours cela n'arrive presque jamais.