Skip to main content
Participant
February 24, 2025
Question

SOLUTION: Count colors used in an image [Branched from 2009 topic]

  • February 24, 2025
  • 2 replies
  • 228 views

Add-Type -AssemblyName System.Drawing

function Get-UniqueColorCount {
param (
[string]$ImagePath
)

if (-Not (Test-Path $ImagePath)) {
Write-Host "File not found: $ImagePath"
return
}

$bitmap = [System.Drawing.Bitmap]::FromFile($ImagePath)
$colors = @{}

for ($x = 0; $x -lt $bitmap.Width; $x++) {
for ($y = 0; $y -lt $bitmap.Height; $y++) {
$color = $bitmap.GetPixel($x, $y).ToArgb()
$colors[$color] = $true
}
}

$bitmap.Dispose()
Write-Host "Unique colors in '$ImagePath': $($colors.Count)"
}

# Example usage:
Get-UniqueColorCount "C:\path\to\your\image.jpg"

 

2 replies

Participant
March 7, 2025

Thank you very much for this, Danijel.

 

My use case involved looking at contour shading with terrain maps--each pixel represents a position in space and a height above sea level (or some normalized variation). In this instance, there were 660, so using Indexed colors wouldn't have given me the right info.

Participant
February 24, 2025

Open PowerShell ISE, paste, all before Example usage, press enter, and execute command with your path in same PowerShell ISE .