首页 > 解决方案 > 将 FromArgb 用于 Int32[] 值会导致交换红色和蓝色值

问题描述

我有这个Int32[]14508153应该是:

R             : 121
G             : 96
B             : 221

在此处输入图像描述


如果我使用:

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

它返回:


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

问题

  1. 这些值如何或为什么被交换RB使用该函数?

  2. 是否有内置的 PowerShell 方法可以正确转换它们?

标签: powershell

解决方案


我无法说明为什么需要重新排列字节(请参阅底部的想法),但可以这样做:

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)
)

System.BitConverter.GetBytes()System.BitConverter.ToInt32()

以上产生:

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

您的( ) 值中似乎只有3个字节是相关的,并且它们是Big-Endian顺序(请参阅关于endianness的维基百科文章)。[int]System.Int32

相比之下,System.Drawing.Color.FromArgb()期望所有 4个字节都是相关的,按照Little-Endian顺序。


推荐阅读