Skip to content

Instantly share code, notes, and snippets.

@noweh
Created September 21, 2021 10:52
Show Gist options
  • Save noweh/9ca56fe38a8c2376b547f882fc67afc7 to your computer and use it in GitHub Desktop.
Save noweh/9ca56fe38a8c2376b547f882fc67afc7 to your computer and use it in GitHub Desktop.
Create a Video Thumbnail from MP4 with FFMPEG
<?php
use Storage;
$file = 'route/to/file.mp4';
$dirThumbnails = 'folder/for/thumbnails';
$thumbnailGroupQuantity = 60;
$thumbnailLineQuantity = 6;
$secondsBetweenTwoThumbnails = 5;
$size = 128;
$responseForFFMPEG = invoke_shell('ffmpeg -version');
if (0 === $responseForFFMPEG->status) {
// Storage in own server, in public/medias folder
$storage = Storage::disk('medias');
// Command to retrieve all frames/$secondsBetweenTwoThumbnails seconds from a video
$response = invoke_shell(
'ffmpeg -i ' . $file .
' -vf "fps=1/' . $secondsBetweenTwoThumbnails . ',' .
' scale=-2:' . $size . '" ' .
'-start_number 0 ' . $dirThumbnails . '/%10d.jpg'
);
if (0 === $response->status) {
$files = glob($dirThumbnails . '/*');
// Put images in group of $thumbnailGroupQuantity images, and create a json with coordinates
for ($groupIndex = 0; $groupIndex < ceil(count($files) / $thumbnailGroupQuantity); ++$groupIndex) {
$groupPath = array_slice(
$files,
$groupIndex * $thumbnailGroupQuantity,
$thumbnailGroupQuantity
);
$coordinates = [];
$jpg = null;
// Place images on line of thumbnailLineQuantity items
for ($lineIndex = 0; $lineIndex < ceil(count($groupPath) / $thumbnailLineQuantity); ++$lineIndex) {
$linePath = array_slice(
$groupPath,
$lineIndex * $thumbnailLineQuantity,
$thumbnailLineQuantity
);
foreach ($linePath as $pathIndex => $path) {
$imageInfos = getimagesize($path);
[$imageWidth, $imageHeight] = $imageInfos;
$coordinatesX = $imageWidth * $pathIndex;
$coordinatesY = $imageHeight * $lineIndex;
if (!is_resource($jpg)) {
$jpg = imagecreatetruecolor(
$imageWidth * count($linePath),
$imageHeight * ceil(count($groupPath) / $thumbnailLineQuantity)
);
}
$imgSrc = imagecreatefromjpeg($path);
imagecopyresized(
$jpg,
$imgSrc,
$coordinatesX,
$coordinatesY,
0,
0,
$imageWidth,
$imageHeight,
$imageWidth,
$imageHeight
);
// Add coordinates in array for .json
$coordinates[] = [
'x' => $coordinatesX,
'y' => $coordinatesY,
'width' => $imageWidth,
'height' => $imageHeight
];
}
}
imagejpeg($jpg, $dirThumbnails . '/sprite-' . $groupIndex . '.jpg');
$storage->put(
$dirThumbnails .'/sprite-' . $groupIndex . '.json',
try_json_encode($coordinates)
);
if (isset($jpg) && is_resource($jpg)) {
imagedestroy($jpg);
$jpg = null;
}
// Clean useless .jpg
array_map('unlink', $files);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment