Skip to content

Instantly share code, notes, and snippets.

@Alistair1231
Last active February 22, 2024 16:26
Show Gist options
  • Save Alistair1231/e8d38d9f3c7a6670a2bc78df234c36be to your computer and use it in GitHub Desktop.
Save Alistair1231/e8d38d9f3c7a6670a2bc78df234c36be to your computer and use it in GitHub Desktop.
crop video to 16:9 with powershell and ffmpeg
# Check if an argument is provided
if ($args.Count -eq 0) {
Write-Host "No video file provided. Usage: .\script.ps1 [video file]"
exit
}
# Assign the first argument as the input file
$inputFile = $args[0]
# Check if the file exists
if (-not (Test-Path $inputFile)) {
Write-Host "File not found: $inputFile"
exit
}
# Get video resolution using FFmpeg
$ffmpegMatches = $(ffmpeg -i $inputFile 2>&1) | sls -pattern "Stream.*Video:.* (\d{3,})x(\d{3,})"
$width = $ffmpegMatches.Matches.Groups[1].Value
$height = $ffmpegMatches.Matches.Groups[2].Value
# Display the current resolution
Write-Host "Current Resolution: $width x $height"
# Calculate new dimensions for 16:9 aspect ratio
$newWidth = [int]$height * 16 / 9
$newHeight = [int]$height
# Display the new dimensions and ask for confirmation
Write-Host "New Resolution (16:9): $newWidth x $newHeight"
# Calculate the crop values (assuming center crop)
$x = ($width - $newWidth) / 2
$y = 0
# Run FFmpeg to crop the video
$outputFile = "cropped_" + $(Get-ChildItem $inputFile).Name
$inputFileFolder = (Get-Item $inputFile).Directory.FullName
$outputFile = Join-Path $inputFileFolder $outputFile
$command = "ffmpeg -i $inputFile -vcodec h264_nvenc -acodec copy -vf `"crop=${newWidth}:${newHeight}:${x}:${y}`" $outputFile"
Write-Host "Running command: `n$command"
$confirmation = Read-Host "Proceed with this command? (Ctrl+C to cancel))"
if ($confirmation -eq "") {
Invoke-Expression $command
Write-Host "Cropping complete. Output file: $outputFile"
}
else {
Write-Host "Operation cancelled by user."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment