Search code examples
powershellimagepixel

Get colour of a pixel from an image file using PowerShell


I'm trying to get the colour of a pixel from an image file using PowerShell. The code I have tried just returns the same values every single time even for different pixels which are different colours. This doesn't seem to be working correctly. I've tired saving the image file as bitmap or png or jpg. I would prefer it worked with a png if thats possible somehow.

$filename = "T1.bmp"
$image = New-Object System.Drawing.Bitmap $filename
$pixelColor = $null
$pixelColor = $image.GetPixel($104, $919)
$pixelColor

$image = New-Object System.Drawing.Bitmap $filename
$pixelColor = $null
$pixelColor = $image.GetPixel($1191, $300)
$pixelColor

Solution

  • It looks like you were passing in variables to the function

    $pixelColor = $image.GetPixel($104, $919)
    $pixelColor = $image.GetPixel($1191, $300)
    

    Unless you had values assigned to $104, $919 or $1191, $300 it most likely is just grabbing the pixel from 0,0 and is the same. Changing to:

    $pixelColor = $image.GetPixel(104, 919)
    $pixelColor = $image.GetPixel(1191, 300)
    

    Should fix the issue.