Using FromArgb for Int32[] value results in swapped Red and Blue values

Viewed 39

I have this Int32[] value 14508153 which should be:

R             : 121
G             : 96
B             : 221

enter image description here


If I use:

[System.Drawing.Color]::FromArgb(14508153)

It returns:


R             : 221
G             : 96
B             : 121
A             : 0
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : dd6079

Questions

  1. How or why are those values swapped for R and B using that function?

  2. Is there a built-in PowerShell method to convert them correctly?

1 Answers

I can't speak to why the bytes need to be rearranged (see the bottom section for thoughts), but here's how you can do it:

Add-Type -AssemblyName System.Drawing

$bytes = [System.BitConverter]::GetBytes(14508153)

[byte[]] $rearrangedBytes = $bytes[2], $bytes[1], $bytes[0], $bytes[3]

[System.Drawing.Color]::FromArgb(
  [System.BitConverter]::ToInt32($rearrangedBytes, 0)
)

See System.BitConverter.GetBytes(), System.BitConverter.ToInt32().

The above yields:

R             : 121
G             : 96
B             : 221
A             : 0
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : 7960dd

It appears that only 3 of the bytes in your [int] (System.Int32) value are relevant, and that they are in Big-Endian order (see the Wikipedia article about endianness).

By contrast, System.Drawing.Color.FromArgb() expects all 4 bytes to be relevant, in Little-Endian order.

Related