Last active
February 22, 2024 16:26
-
-
Save Alistair1231/e8d38d9f3c7a6670a2bc78df234c36be to your computer and use it in GitHub Desktop.
crop video to 16:9 with powershell and ffmpeg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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