使用 php GD 创建 MP4 视频缩略图

Posted

技术标签:

【中文标题】使用 php GD 创建 MP4 视频缩略图【英文标题】:MP4 Video Thumbnail create using php GD 【发布时间】:2014-09-25 15:00:21 【问题描述】:

我正在使用GD图像库上传视频,但我无法创建任何缩略图,有没有办法使用php gb图像库创建mp4视频文件缩略图?

这是我的代码;可以集成ffmpeg吗?

<?php
if(isset($_POST))


############ Edit settings ##############
$ThumbSquareSize        = 400; //Thumbnail will be 200x200
$ThumbPrefix            = "thumb_"; //Normal thumb Prefix
$DestinationDirectory   = 'uploads/'; //specify upload directory ends with / (slash)
$Quality                = 90; //jpeg quality
##########################################

//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']))
    die();


// check $_FILES['ImageFile'] not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))

        die('Something wrong with uploaded file, something missing!'); // output error when above checks fail.


// Random number will be added after image name
$RandomNumber   = rand(0, 9999999999); 

$ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); //get image name
$ImageSize      = $_FILES['ImageFile']['size']; // get original image size
$TempSrc        = $_FILES['ImageFile']['tmp_name']; // Temp name of image file stored in PHP tmp folder
$ImageType      = $_FILES['ImageFile']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.

//Let's check allowed $ImageType, we use PHP SWITCH statement here
switch(strtolower($ImageType))

    case 'video/mp4':
        break;
    default:
        die('Unsupported File!'); //output error and exit


//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
//Get first two values from image, width and height. 
//list assign svalues to $CurWidth,$CurHeight
list($CurWidth,$CurHeight)=getimagesize($TempSrc);

//Get file extension from Image name, this will be added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);

//remove extension from filename
$ImageName      = preg_replace("/\\.[^.\\s]3,4$/", "", $ImageName); 

//Construct a new name with random number and extension.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$pageurl = 'http://'.@$_SERVER['HTTP_HOST'].strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/').'';
//set the Destination Image
$thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
$DestRandImageName          = $DestinationDirectory.$NewImageName; // Image with destination directory

//Resize image to Specified Size by calling resizeImage function.
if(move_uploaded_file($_FILES['ImageFile']['tmp_name'], $DestinationDirectory.$NewImageName ))

    //Create a square Thumbnail right after, this time we are using cropImage() function
    if(!resizeImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$Quality,$ImageType))
        
            echo 'Error Creating thumbnail';
        
    /*
    We have succesfully resized and created thumbnail image
    We can now output image to user's browser or store information in the database
    */
$variable = <<<XYZ
<div class="kingimgupload">
<iframe src="$pageurl/uploads/$NewImageName" ></iframe>
<img src="$pageurl/uploads/$ThumbPrefix$NewImageName" >
</div>
XYZ;
echo $variable;
    /*
    // Insert info into database table!
    mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
    VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
    */

else
    die('Resize Error'); //output error




// This function will proportionally resize image 
function         resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)

//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0) 

    return false;


//Construct a proportional size of new image
$ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurWidth); 
$NewWidth           = ceil($ImageScale*$CurWidth);
$NewHeight          = ceil($ImageScale*$CurHeight);
$NewCanves          = imagecreatetruecolor($NewWidth, $NewHeight);

// Resize Image
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))

    switch(strtolower($ImageType))
    
        case 'video/mp4':
            imagepng($NewCanves,$DestFolder);
            break;
        default:
            return false;
    
//Destroy image, frees memory   
if(is_resource($NewCanves)) imagedestroy($NewCanves); 
return true;



【问题讨论】:

看一下ffmpeg 但并非所有服务器都支持 ffmpeg 确定每个服务器都支持ffmpeg。您的意思是,可能是共享托管环境。无法想象那里有这样的环境,允许电影托管...... 用gd不行吗? 【参考方案1】:

不,你不能使用 GD 来做到这一点。

查看文档

http://php.net/manual/de/book.image.php

您只有以下imagecreatefrom* 函数:

imagecreatefromgd2
imagecreatefromgd2part
imagecreatefromgd
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromstring
imagecreatefromwbmp
imagecreatefromwebp
imagecreatefromxbm
imagecreatefromxpm

没有视频格式。所以不,这是不可能的。

看看FFMpeg 并考虑这个库:

FFMpeg:https://www.ffmpeg.org/

PHP 库:https://github.com/PHP-FFMpeg/PHP-FFMpeg/

当然它没有安装在大多数共享环境中,但是如果你查看它的合同,你会发现,视频托管是不允许的。

当然还有其他可能性,但我无法想象只有 PHP 的方法。

【讨论】:

【参考方案2】:

使用这个简单的代码:

$video_path = 'D:\xampp\htdocs/test.mp4';
$video_image_dir = 'D:\xampp\htdocs/';
$video_name = 'teat.mp4';
$time_in_seconds = round(1 / 2); 
exec("ffmpeg -vframes 1 -ss " . $time_in_seconds . " -i " . $video_path . " " . $video_image_dir . $video_name . ".jpg -y 2> " . $video_image_dir . $video_name . ".txt");

【讨论】:

使用 ffmpeg 很聪明 :-)【参考方案3】:

是的,可以使用 ffmpeg。

在您的服务器中安装 ffmpeg。 查看下面的示例代码。

extension_loaded('ffmpeg') 或 die('加载 ffmpeg 时出错');

// $vid = realpath('./video/Wildlife.wmv');

$video_url = 'http://download.wavetlan.com/SVV/Media/HTTP/H264/Talkinghead_Media/H264_test1_Talkinghead_mp4_480x360.mp4';

$image_filename = 'images/' . time() . ".jpg";

$movie = new ffmpeg_movie($video_url, false);

$frameCount = $movie->getFrameCount();

$capPos = ceil($frameCount / 4);

$frameObject = $movie->getFrame($capPos);

if ($frameObject) 

    $frameObject->resize(500, 250, 0, 0, 0, 0);

    imagejpeg($frameObject->toGDImage());

 else 

    echo 'error';


【讨论】:

以上是关于使用 php GD 创建 MP4 视频缩略图的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 php gd 创建自定义缩略图

PHP 使用GD创建缩略图维持宽高比

为文件夹中的一堆 mp4 视频生成缩略图

使用ffmpeg从视频制作多个缩略图

GD创建图像缩略图

PHP缩略图组件的使用?