Skip to content

Instantly share code, notes, and snippets.

@bitsydoge
Last active May 16, 2023 01:51
Show Gist options
  • Save bitsydoge/8e29dda73c29e614e0184443f98b3eaf to your computer and use it in GitHub Desktop.
Save bitsydoge/8e29dda73c29e614e0184443f98b3eaf to your computer and use it in GitHub Desktop.
param (
[Parameter(Mandatory = $true)]
[ValidateScript({Test-Path $_ -PathType Leaf})]
[String]$ImagePath,
[Parameter(Mandatory = $true)]
[ValidateRange(1, [int]::MaxValue)]
[Int32]$CasesX,
[Parameter(Mandatory = $true)]
[ValidateRange(1, [int]::MaxValue)]
[Int32]$CasesY,
[Parameter(Mandatory = $true)]
[String]$NewBaseName,
[Parameter(Mandatory = $false)]
[ValidateRange(0, [int]::MaxValue)]
[Int32]$StartingNumber = 0
)
try {
# Load the image using .NET Framework
$bitmap = New-Object System.Drawing.Bitmap($ImagePath)
# Calculate the width and height of each slice
$sliceWidth = [int]([Math]::Floor($bitmap.Width / $CasesX))
$sliceHeight = [int]([Math]::Floor($bitmap.Height / $CasesY))
# Iterate over each slice and save it as a separate image with renamed sequential name
$count = $StartingNumber
for ($y = 0; $y -lt $CasesY; $y++) {
for ($x = 0; $x -lt $CasesX; $x++) {
# Create a new bitmap for the current slice
$slice = New-Object System.Drawing.Bitmap($sliceWidth, $sliceHeight)
# Copy the pixels from the original image to the slice
for ($i = 0; $i -lt $sliceWidth; $i++) {
for ($j = 0; $j -lt $sliceHeight; $j++) {
$sourceX = $x * $sliceWidth + $i
$sourceY = $y * $sliceHeight + $j
try {
$pixel = $bitmap.GetPixel($sourceX, $sourceY)
$slice.SetPixel($i, $j, $pixel)
} catch {
Write-Host "Error occurred while processing slice ($x, $y). Details: $_"
}
}
}
# Save the slice as a separate image with padded sequential name
$paddedCount = $count.ToString().PadLeft([math]::Ceiling([math]::Log10(($CasesX * $CasesY) + $StartingNumber)), '0')
$slicePath = "$NewBaseName$paddedCount.png"
$slice.Save($slicePath, [System.Drawing.Imaging.ImageFormat]::Png)
# Dispose the slice bitmap to release resources
$slice.Dispose()
Write-Host "Saved slice: $slicePath"
$count++
}
}
# Dispose the original image bitmap to release resources
$bitmap.Dispose()
Write-Host "Image slicing and renaming completed successfully."
} catch {
Write-Host "An error occurred while processing the image. Details: $_"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment