Created
April 17, 2023 17:49
-
-
Save henno/4f183e3719b52f64edc8b92a19c035de to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Set the desired quality for image compression | |
$quality = 75 | |
# Set the maximum dimensions for resizing while preserving the aspect ratio | |
$maxDimension = "1920x1920>" | |
# Set the minimum file size for resizing and compression (500KB) | |
$minFileSizeForResize = 500 * 1024 | |
# Function to get the date taken from the image's EXIF data | |
function Get-DateTaken { | |
param([string]$imagePath) | |
# Get the DateTimeOriginal and DateTime values from the image's EXIF data | |
$dateTakenInfo = magick identify -format "%[EXIF:DateTimeOriginal]|%[EXIF:DateTime]" $imagePath | |
$dateTimeOriginal, $dateTime = $dateTakenInfo -split '\|' | |
# Try to parse DateTimeOriginal, if available | |
if ($dateTimeOriginal) { | |
try { | |
return [DateTime]::ParseExact($dateTimeOriginal, "yyyy:MM:dd HH:mm:ss", $null) | |
} catch { | |
return $null | |
} | |
# If DateTimeOriginal is not available, try to parse DateTime | |
} elseif ($dateTime) { | |
try { | |
return [DateTime]::ParseExact($dateTime, "yyyy:MM:dd HH:mm:ss", $null) | |
} catch { | |
return $null | |
} | |
} | |
# If neither DateTimeOriginal nor DateTime is available, return null | |
return $null | |
} | |
# Get all .jpg and .jpeg files in the current directory and its subdirectories | |
Get-ChildItem -Path . -Include *.jpg, *.jpeg -Recurse | ForEach-Object { | |
Write-Host "Processing $($_.FullName)" | |
# Get the date taken from the image's EXIF data | |
$dateTaken = Get-DateTaken $_.FullName | |
# If the date taken is not available, use the file's last write time | |
if (-not $dateTaken) { | |
$dateTaken = $_.LastWriteTime | |
} | |
# If the file size is larger than the minimum file size for resizing and compression | |
if ($_.Length -gt $minFileSizeForResize) { | |
# Create a temporary file path for the compressed image | |
$compressedImagePath = "$($_.DirectoryName)\compressed_$($_.Name)" | |
# Resize and compress the image | |
magick convert $_.FullName -resize $maxDimension -quality $quality $compressedImagePath | |
# Remove the original image | |
Remove-Item $_.FullName | |
# Rename the compressed image to the original file name | |
Rename-Item $compressedImagePath $_.Name | |
} | |
# Check if the file's date is already correct before updating it | |
if ((Get-Item $_.Name).LastWriteTime -ne $dateTaken) { | |
# Update the file date with the date taken | |
(Get-Item $_.Name).LastWriteTime = $dateTaken | |
} | |
Write-Host "Completed $($_.FullName)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment