public function actionThumbnail($params) { $attachment = new Model_Attachment($this->getStorage(), $params['id']); if ($attachment->getId()) { if ($attachment->isImage()) { $file = $attachment->getFilepath(); } elseif ($attachment->isVideo()) { if (class_exists("ffmpeg_movie")) { $film = new ffmpeg_movie($attachment->getFilepath()); $frame = ceil($film->getFrameCount() * 0.1); $file = $film->getFrame($frame)->toGDImage(); } else { $this->imageNotFound(); } } else { $this->imageNotFound(); } $view = new View_Image_Gd2($file); if ($view) { $view->scale($params['scale']); } else { $this->imageNotFound(); } } else { $this->imageNotFound(); } return $view; }
public function getVideoSize($fileName) { $ffmpegInstance = new ffmpeg_movie($fileName); $video_size['width'] = $ffmpegInstance->getFrameWidth(); $video_size['height'] = $ffmpegInstance->getFrameHeight(); $video_size['duration'] = $ffmpegInstance->getDuration(); $video_size['frame_rate'] = $ffmpegInstance->getFrameRate(); $video_size['frame_count'] = $ffmpegInstance->getFrameCount(); return $video_size; }
/** * @overload Canvas::construct(); * * Take a screenshot and return the image */ function __construct($filename, $frame = null) { if (!extension_loaded('ffmpeg')) { throw new BaseException("The FFMPEG extension is not loaded!"); } else { $movie = new ffmpeg_movie($filename); if ($frame == null) { $frame = floor($movie->getFrameCount()); } $frameimg = $movie->getFrame($frame); } if ($frameimg) { $sc = $frameimg->toGDImage(); $this->setImage($sc); } else { throw new GraphicsException("Failed to capture frame!"); } }
/** * Create an thumbnail from a video. Returns null if the creation failed. * * @param string $originalPath the path of the orignal video * @param string $destinationPath the path were the thumbnail will be copied * @param int $newWidth the width of the thumbnail * @param int $newHeight the width of the thumbnail * * @return string */ public function fromVideo($originalPath, $destinationPath, $newWidth, $newHeight) { if (!$this->isGdLoaded || !$this->isFfmpegLoaded) { $message = ''; if (!$this->isGdLoaded) { $message .= 'The GD extension is missing \\n'; } if (!$this->isFfmpegLoaded) { $message .= 'The Ffmpeg extension is missing \\n'; } throw new UnloadedExtensionException($message); } $media = new \ffmpeg_movie($originalPath); $frameCount = $media->getFrameCount(); $frame = $media->getFrame(round($frameCount / 2)); if ($frame) { $image = $frame->toGDImage(); $this->resize($newWidth, $newHeight, $image, $destinationPath); return $destinationPath; } $exception = new ExtensionNotSupportedException(); $exception->setExtension(pathinfo($originalPath, PATHINFO_EXTENSION)); throw $exception; }
echo '<pre>'; } printf("ffmpeg-php version string: %s\n", FFMPEG_PHP_VERSION_STRING); printf("ffmpeg-php build date string: %s\n", FFMPEG_PHP_BUILD_DATE_STRING); printf("libavcodec build number: %d\n", LIBAVCODEC_BUILD_NUMBER); printf("libavcodec version number: %d\n", LIBAVCODEC_VERSION_NUMBER); print_class_methods("ffmpeg_movie"); print_class_methods("ffmpeg_frame"); // get an array for movies from the test media directory $movies = getDirFiles(dirname(__FILE__) . '/tests/test_media'); echo "--------------------\n\n"; foreach ($movies as $movie) { $mov = new ffmpeg_movie($movie); printf("file name = %s\n", $mov->getFileName()); printf("duration = %s seconds\n", $mov->getDuration()); printf("frame count = %s\n", $mov->getFrameCount()); printf("frame rate = %0.3f fps\n", $mov->getFrameRate()); printf("comment = %s\n", $mov->getComment()); printf("title = %s\n", $mov->getTitle()); printf("author = %s\n", $mov->getAuthor()); printf("copyright = %s\n", $mov->getCopyright()); printf("get bit rate = %d\n", $mov->getBitRate()); printf("has audio = %s\n", $mov->hasAudio() == 0 ? 'No' : 'Yes'); if ($mov->hasAudio()) { printf("get audio stream id= %s\n", $mov->getAudioStreamId()); printf("get audio codec = %s\n", $mov->getAudioCodec()); printf("get audio bit rate = %d\n", $mov->getAudioBitRate()); printf("get audio sample rate = %d \n", $mov->getAudioSampleRate()); printf("get audio channels = %s\n", $mov->getAudioChannels()); } printf("has video = %s\n", $mov->hasVideo() == 0 ? 'No' : 'Yes');
echo '<img src="processed/thumbnails/' . $file_info['filename'] . '-cropped.jpg" alt="" width="' . $frame->getWidth() . '" height="' . $frame->getHeight() . '" border="0" /><br /><br />'; // resize the thumbnail $frame->resize(50, 50); $gd_resource = $frame->toGDImage(); imagejpeg($gd_resource, PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/' . $file_info['filename'] . '-resized.jpg', 80); $small_width = $frame->getWidth(); $small_height = $frame->getHeight(); echo '<strong>Cropped and Resized Frame Grab of Movie</strong>.<br />'; echo 'This is a frame grab that has been cropped then resized.<br />'; echo '<img src="processed/thumbnails/' . $file_info['filename'] . '-resized.jpg" alt="" width="' . $small_width . '" height="' . $small_height . '" border="0" /><br /><br />'; // create 2 animated gifs, one normal size, one small // create the normal one $ffmpeg_gif = new ffmpeg_animated_gif(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/' . $file_info['filename'] . '-animated.gif', $orig_width, $orig_height, 5, 0); // create the small one $ffmpeg_gif_small = new ffmpeg_animated_gif(PHPVIDEOTOOLKIT_EXAMPLE_ABSOLUTE_BATH . 'processed/thumbnails/' . $file_info['filename'] . '-animated-small.gif', $small_width, $small_height, 5, 0); for ($i = 1, $a = $ffmpeg_movie->getFrameCount(), $inc = $ffmpeg_movie->getFrameRate() / 2; $i < $a; $i += $inc) { // get the required frame $ffmpeg_frame = $ffmpeg_movie->getFrame($i); if ($ffmpeg_frame !== false) { // add the frame to the gif $result = $ffmpeg_gif->addFrame($ffmpeg_frame); if (!$result) { 'There was an error adding frame ' . $i . ' to the gif.<br />'; } } // get the required frame $ffmpeg_frame_small = $ffmpeg_movie->getFrame($i); if ($ffmpeg_frame_small !== false) { // crop and resize the frame $ffmpeg_frame_small->resize(50, 50, 20, 20, 20, 20); // then add it to the small one
/** * Add a post */ public function iframe_add() { $this->setView('iframe_add.php'); @set_time_limit(0); $uploaded_files = array(); try { if (!isset(User_Model::$auth_data)) { throw new Exception(__('POST_ADD_ERROR_SESSION_EXPIRED')); } $is_student = isset(User_Model::$auth_data['student_number']); // Message $message = isset($_POST['message']) ? trim($_POST['message']) : ''; if ($message == '' || $message == __('PUBLISH_DEFAULT_MESSAGE')) { throw new Exception(__('POST_ADD_ERROR_NO_MESSAGE')); } $message = preg_replace('#\\n{2,}#', "\n\n", $message); // Category if (!isset($_POST['category']) || !ctype_digit($_POST['category'])) { throw new Exception(__('POST_ADD_ERROR_NO_CATEGORY')); } $category = (int) $_POST['category']; // Official post (in a group) $official = isset($_POST['official']); // Group $group = isset($_POST['group']) && ctype_digit($_POST['group']) ? (int) $_POST['group'] : 0; if ($group == 0) { $group = null; $official = false; } else { $groups_auth = Group_Model::getAuth(); if (isset($groups_auth[$group])) { if ($official && !$groups_auth[$group]['admin']) { throw new Exception(__('POST_ADD_ERROR_OFFICIAL')); } } else { throw new Exception(__('POST_ADD_ERROR_GROUP_NOT_FOUND')); } } // Private message $private = isset($_POST['private']); if ($private && !$is_student) { throw new Exception(__('POST_ADD_ERROR_PRIVATE')); } $attachments = array(); // Photos if (isset($_FILES['attachment_photo']) && is_array($_FILES['attachment_photo']['name'])) { foreach ($_FILES['attachment_photo']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_PHOTO) { throw new Exception(__('POST_ADD_ERROR_PHOTO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_PHOTO)))); } } if ($filepaths = File::upload('attachment_photo')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_photo']['name'][$i]) ? $_FILES['attachment_photo']['name'][$i] : ''; try { $img = new Image(); $img->load($filepath); $type = $img->getType(); if ($type == IMAGETYPE_JPEG) { $ext = 'jpg'; } else { if ($type == IMAGETYPE_GIF) { $ext = 'gif'; } else { if ($type == IMAGETYPE_PNG) { $ext = 'png'; } else { throw new Exception(); } } } if ($img->getWidth() > 800) { $img->setWidth(800, true); } $img->save($filepath); // Thumb $thumbpath = $filepath . '.thumb'; $img->thumb(Config::$THUMBS_SIZES[0], Config::$THUMBS_SIZES[1]); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); unset($img); $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $thumbpath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_PHOTO_FORMAT')); } } } } // Vidéos /* @uses PHPVideoToolkit : http://code.google.com/p/phpvideotoolkit/ * @requires ffmpeg, php5-ffmpeg */ if (isset($_FILES['attachment_video']) && is_array($_FILES['attachment_video']['name'])) { foreach ($_FILES['attachment_video']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_VIDEO) { throw new Exception(__('POST_ADD_ERROR_VIDEO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_VIDEO)))); } } if ($filepaths = File::upload('attachment_video')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { $name = isset($_FILES['attachment_video']['name'][$i]) ? $_FILES['attachment_video']['name'][$i] : ''; try { $video = new ffmpeg_movie($filepath, false); if (!$video->hasVideo()) { throw new Exception('No video stream found in the file'); } if (!$video->hasAudio()) { throw new Exception('No audio stream found in the file'); } } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_FORMAT')); } // Video conversion try { $video_current_width = $video->getFrameWidth(); $video_width = min($video_current_width, Config::VIDEO_MAX_WIDTH); if ($video_width % 2 == 1) { // Even number required $video_width--; } $video_height = $video_width * $video->getFrameHeight() / $video_current_width; if ($video_height % 2 == 1) { // Even number required $video_height--; } // Extract thumb $video_thumb = $video->getFrame(round($video->getFrameCount() * 0.2)); unset($video); $video_thumb = $video_thumb->toGDImage(); $thumbpath = DATA_DIR . Config::DIR_DATA_TMP . File::getName($filepath) . '.thumb'; imagejpeg($video_thumb, $thumbpath, 95); unset($video_thumb); $img = new Image(); $img->load($thumbpath); $img->setWidth($video_width, true); $img->setType(IMAGETYPE_JPEG); $img->save($thumbpath); $uploaded_files[] = $thumbpath; unset($img); // Convert to FLV if (!preg_match('#\\.flv$#i', $filepath)) { $toolkit = new PHPVideoToolkit(); $toolkit->on_error_die = true; // Will throw exception on error $toolkit->setInputFile($filepath); $toolkit->setVideoOutputDimensions($video_width, $video_height); $toolkit->setFormatToFLV(Config::VIDEO_SAMPLING_RATE, Config::VIDEO_AUDIO_BIT_RATE); $toolkit->setOutput(DATA_DIR . Config::DIR_DATA_TMP, File::getName($filepath) . '.flv', PHPVideoToolkit::OVERWRITE_EXISTING); $toolkit->execute(false, false); // Multipass: false, Log: false File::delete($filepath); $filepath = $toolkit->getLastOutput(); $filepath = $filepath[0]; unset($toolkit); } $attachments[] = array($filepath, $name, $thumbpath); $uploaded_files[] = $filepath; } catch (Exception $e) { throw new Exception(__('POST_ADD_ERROR_VIDEO_CONVERT') . $e->getMessage()); } } } } // Audios if (isset($_FILES['attachment_audio']) && is_array($_FILES['attachment_audio']['name'])) { foreach ($_FILES['attachment_audio']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_AUDIO) { throw new Exception(__('POST_ADD_ERROR_AUDIO_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_AUDIO)))); } } if ($filepaths = File::upload('attachment_audio')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.mp3$#', $filepath)) { throw new Exception(__('POST_ADD_ERROR_AUDIO_FORMAT')); } $name = isset($_FILES['attachment_audio']['name'][$i]) ? $_FILES['attachment_audio']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Files if (isset($_FILES['attachment_file']) && is_array($_FILES['attachment_file']['name'])) { foreach ($_FILES['attachment_file']['size'] as $size) { if ($size > Config::UPLOAD_MAX_SIZE_FILE) { throw new Exception(__('POST_ADD_ERROR_FILE_SIZE', array('size' => File::humanReadableSize(Config::UPLOAD_MAX_SIZE_FILE)))); } } if ($filepaths = File::upload('attachment_file')) { foreach ($filepaths as $filepath) { $uploaded_files[] = $filepath; } foreach ($filepaths as $i => $filepath) { if (!preg_match('#\\.[a-z0-9]{2,4}$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT')); } if (preg_match('#\\.(jpg|png|gif|mp3|flv)$#i', $filepath)) { throw new Exception(__('POST_ADD_ERROR_FILE_FORMAT2')); } $name = isset($_FILES['attachment_file']['name'][$i]) ? $_FILES['attachment_file']['name'][$i] : ''; $attachments[] = array($filepath, $name); } } } // Event if (isset($_POST['event_title']) && isset($_POST['event_start']) && isset($_POST['event_end'])) { // Title $event_title = trim($_POST['event_title']); if ($event_title == '') { throw new Exception(__('POST_ADD_ERROR_EVENT_NO_TITLE')); } // Dates if (!($event_start = strptime($_POST['event_start'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } if (!($event_end = strptime($_POST['event_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE')); } $event_start = mktime($event_start['tm_hour'], $event_start['tm_min'], 0, $event_start['tm_mon'] + 1, $event_start['tm_mday'], $event_start['tm_year'] + 1900); $event_end = mktime($event_end['tm_hour'], $event_end['tm_min'], 0, $event_end['tm_mon'] + 1, $event_end['tm_mday'], $event_end['tm_year'] + 1900); if ($event_start > $event_end) { throw new Exception(__('POST_ADD_ERROR_EVENT_DATE_ORDER')); } $event = array($event_title, $event_start, $event_end); } else { $event = null; } // Survey if (isset($_POST['survey_question']) && isset($_POST['survey_end']) && isset($_POST['survey_answer']) && is_array($_POST['survey_answer'])) { // Question $survey_question = trim($_POST['survey_question']); if ($survey_question == '') { throw new Exception(__('POST_ADD_ERROR_SURVEY_NO_QUESTION')); } // Date if (!($survey_end = strptime($_POST['survey_end'], __('PUBLISH_EVENT_DATE_FORMAT')))) { throw new Exception(__('POST_ADD_ERROR_SURVEY_DATE')); } $survey_end = mktime($survey_end['tm_hour'], $survey_end['tm_min'], 0, $survey_end['tm_mon'] + 1, $survey_end['tm_mday'], $survey_end['tm_year'] + 1900); // Multiple answers $survey_multiple = isset($_POST['survey_multiple']); // Answers $survey_answers = array(); foreach ($_POST['survey_answer'] as $survey_answer) { $survey_answer = trim($survey_answer); if ($survey_answer != '') { $survey_answers[] = $survey_answer; } } if (count($survey_answers) < 2) { throw new Exception(__('POST_ADD_ERROR_SURVEY_ANSWERS')); } $survey = array($survey_question, $survey_end, $survey_multiple, $survey_answers); } else { $survey = null; } // Creation of the post $id = $this->model->addPost((int) User_Model::$auth_data['id'], $message, $category, $group, $official, $private); // Attach files foreach ($attachments as $attachment) { $this->model->attachFile($id, $attachment[0], $attachment[1], isset($attachment[2]) ? $attachment[2] : null); } // Event if (isset($event)) { $this->model->attachEvent($id, $event[0], $event[1], $event[2]); } // Survey if (isset($survey)) { $this->model->attachSurvey($id, $survey[0], $survey[1], $survey[2], $survey[3]); } $this->addJSCode(' parent.location = "' . Config::URL_ROOT . Routes::getPage('home') . '"; '); } catch (Exception $e) { // Delete all uploading files in tmp foreach ($uploaded_files as $uploaded_file) { File::delete($uploaded_file); } $this->addJSCode(' with(parent){ Post.errorForm(' . json_encode($e->getMessage()) . '); } '); } }
public function generateFFMPEG() { $ff = new ffmpeg_movie($this->path . $this->data['path'] . '/' . $this->data['name']); if (!$ff) { $this->unknown = true; return false; } $this->info = array('width' => $ff->getFrameWidth(), 'height' => $ff->getFrameHeight(), 'duration' => $ff->getDuration(), 'mime' => $this->mime, 'size' => filesize($this->path . $this->data['path'] . '/' . $this->data['name'])); if ($ff->getFrameCount() > 20) { $frame = $frame = $ff->getFrame(20); } else { $frame = $frame = $ff->getFrame($ff->getFrameCount() - 1); } $gd = $frame->toGDImage(); $this->generateGDimage($gd, 'video'); $this->updateDB(); }
public function generateFFMPEG() { $ff = new ffmpeg_movie($this->pathname . $this->filename); if (!$ff) { $this->unknown = true; return false; } $this->info = array('width' => $ff->getFrameWidth(), 'height' => $ff->getFrameHeight(), 'duration' => $ff->getDuration(), 'mime' => $this->mime, 'size' => filesize($this->pathname . $this->filename)); if ($ff->getFrameCount() > 20) { $frame = $frame = $ff->getFrame(20); } else { $frame = $frame = $ff->getFrame($ff->getFrameCount() - 1); } $gd = $frame->toGDImage(); imagejpeg($gd, $this->pathcache . $this->getBaseName()); $this->mime = 'image/jpeg'; $this->type = array('video', 'jpeg'); $this->pathname = $this->pathcache; $this->filename = $this->getBaseName(); }
function analyzeMediaFile(&$metaData, $filePath = NULL, $cachePath = NULL) { if (!isset($metaData->fileName) || !isset($metaData->fileType)) { throw new Exception("meta data invalid"); } $file = $filePath . DIRECTORY_SEPARATOR . $metaData->fileName; if (!is_file($file) || !is_readable($file)) { throw new Exception("file does not exist"); } if (!is_dir($cachePath)) { throw new Exception("cache dir does not exist"); } switch ($metaData->fileType) { case "video/quicktime": case "application/ogg": case "audio/mpeg": case "video/mp4": case "video/x-msvideo": case "video/ogg": case "video/webm": case "video/x-ms-asf": case "video/x-flv": case "audio/x-wav": case "application/octet-stream": if (isMediaFile($metaData, $filePath)) { $media = new ffmpeg_movie($file, FALSE); /**************************************************** * VIDEO ****************************************************/ if ($media->hasVideo()) { $metaData->video->codec = $media->getVideoCodec(); $metaData->video->width = $media->getFrameWidth(); $metaData->video->height = $media->getFrameHeight(); $metaData->video->bitrate = $media->getVideoBitRate(); $metaData->video->framerate = $media->getFrameRate(); $metaData->video->duration = $media->getDuration(); /* Video Still */ $stillFile = $cachePath . DIRECTORY_SEPARATOR . uniqid("ft_") . ".png"; $fc = (int) ($media->getFrameCount() / 32); /* frame count is not necessarily reliable! */ foreach (array($fc, 100, 10, 1) as $fno) { if ($fno == 0) { continue; } $f = $media->getFrame($fno); if ($f !== FALSE) { imagepng($f->toGDImage(), $stillFile); $metaData->video->still = basename($stillFile); break; } } /* Video Thumbnails */ $thumbSizes = array(90, 180, 360); foreach ($thumbSizes as $tS) { $thumbFile = $cachePath . DIRECTORY_SEPARATOR . uniqid("ft_") . ".png"; list($thumb_width, $thumb_height) = generateThumbnail($stillFile, $thumbFile, $tS); $metaData->video->thumbnail->{$tS}->file = basename($thumbFile); $metaData->video->thumbnail->{$tS}->width = $thumb_width; $metaData->video->thumbnail->{$tS}->height = $thumb_height; } /* Schedule for transcoding */ $transcodeSizes = array(360); $metaData->transcodeStatus = 'WAITING'; $metaData->transcodeProgress = 0; foreach ($transcodeSizes as $tS) { $transcodeFile = $cachePath . DIRECTORY_SEPARATOR . uniqid("ft_") . ".webm"; list($width, $height) = scaleVideo($media->getFrameWidth(), $media->getFrameHeight(), $tS); $metaData->video->transcode->{$tS}->file = basename($transcodeFile); $metaData->video->transcode->{$tS}->width = $width; $metaData->video->transcode->{$tS}->height = $height; } } /**************************************************** * AUDIO ****************************************************/ if ($media->hasAudio()) { $metaData->audio->codec = $media->getAudioCodec(); $metaData->audio->bitrate = $media->getAudioBitRate(); $metaData->audio->samplerate = $media->getAudioSampleRate(); $metaData->audio->duration = $media->getDuration(); $metaData->transcodeStatus = 'WAITING'; $metaData->transcodeProgress = 0; $transcodeFile = $cachePath . DIRECTORY_SEPARATOR . uniqid("ft_") . ".ogg"; $metaData->audio->transcode->file = basename($transcodeFile); } } else { /* No media? */ } break; case "image/jpeg": case "image/png": case "image/gif": case "image/bmp": list($width, $height) = getimagesize($file); $metaData->image->width = $width; $metaData->image->height = $height; $thumbFile = $cachePath . DIRECTORY_SEPARATOR . uniqid("ft_") . ".png"; list($thumb_width, $thumb_height) = generateThumbnail($file, $thumbFile, 360); $metaData->image->thumbnail->{360}->file = basename($thumbFile); $metaData->image->thumbnail->{360}->width = $thumb_width; $metaData->image->thumbnail->{360}->height = $thumb_height; break; default: /* no idea about this file, let it go... */ } }
function path($param1 = array(), $param2 = array(), $param3 = array()) { if (is_array($param1)) { $path = $param1['path']; $filename = $param1['filename']; $options =& $param2; } else { $path = $param1; $filename = $param2; $options = $param3; } if ($path == '' || $filename == '') { return false; } // Set default values if (!isset($options['full'])) { $options['full'] = false; } if (!isset($options['dims'])) { $options['dims'] = 'original'; } if (isset($options['size'])) { $options['dims'] = $options['size']; } if ($options['dims'] != 'original' && !isset($options['method'])) { $options['method'] = 'crop'; } if (!isset($options['saveas'])) { $options['saveas'] = null; } if (!isset($options['time'])) { $options['time'] = null; } if (!isset($options['watermark'])) { $options['watermark'] = null; } // Path must not begin with slash but must end with slash if ($path[0] == '/') { $path = substr($path, 1); } if (substr($path, -1) != '/') { $path .= '/'; } // Absolute path to directory $absolutePath = WWW_ROOT . $path; // Absolute path to file $absoluteFilePath = $absolutePath . $filename; if (file_exists($absoluteFilePath)) { $fileSize = filesize($absoluteFilePath); $fileExt = strtolower(strrchr($filename, '.')); if ($fileExt == '.jpeg') { $fileExt = '.jpg'; } if (!in_array($fileExt, array('.jpg', '.jpeg', '.png', '.gif', '.f4v', '.flv'))) { return false; } $fileNameNoExt = substr($filename, 0, -strlen($fileExt)); if ($options['saveas'] == null) { if ($fileExt == '.flv' || $fileExt == '.f4v') { $options['saveas'] = '.jpg'; } $options['saveas'] = $fileExt; } else { $options['saveas'] = strtolower($options['saveas']); if ($options['saveas'] == '.jpeg') { $options['saveas'] == '.jpg'; } if ($options['saveas'][0] != '.') { $options['saveas'] = '.' . $options['saveas']; } } if ($options['dims'] == 'original' && $options['saveas'] == $fileExt && $fileExt != '.flv' && $fileExt != '.f4v' && $options['watermark'] == null) { // original file returned return $this->url('/' . $path . $filename, $options['full']); } else { $cachedFile = $this->_cachePath($path, $fileNameNoExt, $fileExt, $fileSize, $options); if ($cachedFile['exists']) { return $this->url($cachedFile['path'] . $cachedFile['filename'], $options['full']); } else { // create file if ($fileExt == '.flv' || $fileExt == '.f4v') { // if video, check if a screenshot already exists $optionsOriginal = $options; $optionsOriginal['dims'] = 'original'; $optionsOriginal['watermark'] = null; $videoScreenshot = $this->_cachePath($path, $fileNameNoExt, $fileExt, $fileSize, $optionsOriginal); if ($videoScreenshot['exists']) { // Screenshot already exists, use it $img = $this->_loadImage($videoScreenshot['path'], $videoScreenshot['filename']); } else { // No screenshot available, take one if (class_exists('ffmpeg_movie')) { $ffmpegInstance = new ffmpeg_movie($absoluteFilePath); if ($options['time'] != null) { // take screenshot at specified time $framerate = $ffmpegInstance->getFrameRate(); $framecount = $ffmpegInstance->getFrameCount(); $frame_number = $framerate * $options['time']; if ($frame_number > $framecount - 1) { // invalid time $frame = $ffmpegInstance->getFrame((int) ($ffmpegInstance->getFrameCount() / 2)); } else { $frame = $ffmpegInstance->getFrame($frame_number); } } else { // take screenshot at middle of video $frame = $ffmpegInstance->getFrame((int) ($ffmpegInstance->getFrameCount() / 2)); } $img = $frame->toGDImage(); // Save screenshot for future use $this->_saveImage($img, $videoScreenshot['path'], $videoScreenshot['filename'], $options['saveas']); } else { return false; } } } else { // this is not a video // load image $img = $this->_loadImage($path, $filename, $fileExt); } // Add watermark if needed if ($options['watermark'] != null) { if ($options['watermark'][0] == '/') { $options['watermark'] = substr($options['watermark'], 1); } $absoluteWatermarkFile = WWW_ROOT . $options['watermark']; if (file_exists($absoluteWatermarkFile)) { $watermarkFileName = basename($options['watermark']); $watermark = $this->_loadImage(dirname($options['watermark']) . '/', $watermarkFileName, strtolower(strrchr($watermarkFileName, '.'))); //var_dump($watermark); //die(); $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); $img_height = imagesy($img); $img_width = imagesx($img); for ($i = 0; $i < $img_width; $i = $i + 1.5 * $watermark_width) { for ($j = 0; $j < $img_height; $j = $j + 1.5 * $watermark_height) { imagecopy($img, $watermark, $i, $j, 0, 0, $watermark_width, $watermark_height); } } } } // crop/resize if needed if ($options['dims'] != 'original') { if ($options['method'] == 'crop') { $img = $this->_crop($img, $options['dims'], $fileExt == '.png' && $options['saveas'] == '.png'); } elseif ($options['method'] == 'resize') { $img = $this->_resize($img, $options['dims'], $fileExt == '.png' && $options['saveas'] == '.png'); } } // Save image if ($this->_saveImage($img, $cachedFile['path'], $cachedFile['filename'], $options['saveas'])) { imagedestroy($img); return $this->url($cachedFile['path'] . $cachedFile['filename'], $options['full']); } return false; } } } return false; }
echo "</td></tr></table>"; echo "<p/>"; print_class_methods("ffmpeg_movie"); echo "<p/>"; print_class_methods("ffmpeg_frame"); // get an array for movies from the test media directory $movies = getDirFiles(dirname(__FILE__) . '/tests/test_media'); $i = 1; foreach ($movies as $movie) { $mov = new ffmpeg_movie($movie); echo '<table width="90%" class="hor-minimalist-a">'; printf('<caption>Processing Test File: %s...</caption>', basename($mov->getFilename())); printf('<thead><tr><th width="150">Method</th><th>Result<br/></th></tr></thead>', $mov->getFileName()); printf("<tr><td>file name:</td><td>%s<br/></td></tr>", $mov->getFileName()); printf("<tr><td>duration</td><td>%s seconds<br/></td></tr>", $mov->getDuration()); printf("<tr><td>frame count</td><td>%s<br/></td></tr>", $mov->getFrameCount()); printf("<tr><td>frame rate</td><td>%0.3f fps<br/></td></tr>", $mov->getFrameRate()); printf("<tr><td>comment</td><td>%s<br/></td></tr>", $mov->getComment()); printf("<tr><td>title</td><td>%s<br/></td></tr>", $mov->getTitle()); printf("<tr><td>author</td><td>%s<br/></td></tr>", $mov->getAuthor()); printf("<tr><td>copyright</td><td>%s<br/></td></tr>", $mov->getCopyright()); printf("<tr><td>get bit rate</td><td>%d<br/></td></tr>", $mov->getBitRate()); printf("<tr><td>has audio</td><td>%s<br/></td></tr>", $mov->hasAudio() == 0 ? 'No' : 'Yes'); if ($mov->hasAudio()) { printf("<tr><td>get audio stream id</td><td>%s<br/></td></tr>", $mov->getAudioStreamId()); printf("<tr><td>get audio codec</td><td>%s<br/></td></tr>", $mov->getAudioCodec()); printf("<tr><td>get audio bit rate</td><td>%d<br/></td></tr>", $mov->getAudioBitRate()); printf("<tr><td>get audio sample rate</td><td>%d<br/></td></tr>", $mov->getAudioSampleRate()); printf("<tr><td>get audio channels</td><td>%s<br/></td></tr>", $mov->getAudioChannels()); } printf("<tr><td>has video</td><td>%s<br/></td></tr>", $mov->hasVideo() == 0 ? 'No' : 'Yes');
public function updateMetadata(MediaInterface $media, $force = false) { $file = sprintf('%s/%s/%s', $this->getFilesystem()->getAdapter()->getDirectory(), $this->generatePath($media), $media->getProviderReference()); $fileinfos = new ffmpeg_movie($file, false); $img_par_s = $fileinfos->getFrameCount() / $fileinfos->getDuration(); // Récupère l'image $frame = $fileinfos->getFrame(15 * $img_par_s); //$media->setContentType($media->getProviderReference()->getMimeType()); $media->setContentType(mime_content_type($file)); $media->setSize(filesize($file)); $media->setWidth($frame->getWidth()); $media->setHeight($frame->getHeight()); $media->setLength($fileinfos->getDuration()); $media->setMetadataValue('bitrate', $fileinfos->getBitRate()); }
function captureVideoPosterImg($movie_file = '') { extension_loaded('ffmpeg'); $movie_file = 'http://upload.freelabel.net/server/php/files/JXL%20%23CrunkDUpTour%20Promo.mp4'; // Instantiates the class ffmpeg_movie so we can get the information you want the video $movie = new ffmpeg_movie($movie_file); // Get The duration of the video in seconds echo $Duration = round($movie->getDuration(), 0); // Get the number of frames of the video $TotalFrames = $movie->getFrameCount(); // Get the height in pixels Video $height = $movie->getFrameHeight(); // Get the width of the video in pixels $width = $movie->getFrameWidth(); //Receiving the frame from the video and saving // Need to create a GD image ffmpeg-php to work on it $image = imagecreatetruecolor($width, $height); // Create an instance of the frame with the class ffmpeg_frame $Frame = new ffmpeg_frame($image); // Choose the frame you want to save as jpeg $thumbnailOf = (int) round($movie->getFrameCount() / 2.5); // Receives the frame $frame = $movie->GetFrame($thumbnailOf); // Convert to a GD image $image = $frame->toGDImage(); // Save to disk. //echo $movie_file.'.jpg'; imagejpeg($image, $movie_file . '.jpg', 100); return $movie_file . '.jpg'; }