.net 对于图像中的每个像素,获取颜色、像素位置和相对于图像的坐标 脚本

.net 对于图像中的每个像素,获取颜色、像素位置和相对于图像的坐标 脚本,.net,vb.net,colors,bitmap,gdi+,.net,Vb.net,Colors,Bitmap,Gdi+,我正在尝试编写一个函数,它将使用下面的结构,PixelInfo,返回源图像中每个像素的集合,该集合将存储颜色、像素位置和一个点,其坐标位置相对于图像: <Serializable> <StructLayout(LayoutKind.Sequential)> Public Structure PixelInfo Public ReadOnly Property Color As Color Get Return Me.col

我正在尝试编写一个函数,它将使用下面的结构,
PixelInfo
,返回源图像中每个像素的集合,该集合将存储
颜色
、像素位置和一个
,其坐标位置相对于图像:

<Serializable>
<StructLayout(LayoutKind.Sequential)>
Public Structure PixelInfo

    Public ReadOnly Property Color As Color
        Get
            Return Me.colorB
        End Get
    End Property
    Private ReadOnly colorB As Color

    Public ReadOnly Property Position As Integer
        Get
            Return Me.positionB
        End Get
    End Property
    Private ReadOnly positionB As Integer

    Public ReadOnly Property Location As Point
        Get
            Return Me.locationB
        End Get
    End Property
    Private ReadOnly locationB As Point

    <DebuggerStepThrough>
    Public Sub New(ByVal color As Color,
                   ByVal position As Integer,
                   ByVal location As Point)

        Me.colorB = color
        Me.positionB = position
        Me.locationB = location

    End Sub

End Structure
这是执行的意外结果:

Position: 0, Location: {X=0,Y=0}, Color: Color [A=255, R=117, G=228, B=26]
Position: 1, Location: {X=1,Y=0}, Color: Color [A=255, R=117, G=228, B=26]
Position: 2, Location: {X=0,Y=1}, Color: Color [A=255, R=26, G=0, B=0]
Position: 3, Location: {X=1,Y=1}, Color: Color [A=255, R=26, G=117, B=228]
Position: 4, Location: {X=0,Y=2}, Color: Color [A=255, R=0, G=117, B=228]
有5个元素(对于5个像素,当图像只有4个像素时),元素2、3和4上的颜色不同

我做错了。

我建议你在维基百科上仔细阅读这篇文章,尤其是这一部分

像素格式由DIB头或额外位掩码定义。像素阵列中的每一行都填充为4字节的倍数

因此,2x2 24bppRgb位图每行中的字节如下所示。如您所见,每行的末尾都有两个“填充字节”

4x2 24bppRgb位图中没有填充,因为每行中的字节正好是3个DWORD


在位图中的行之间移动时,需要考虑BitmapData.Stride属性。在32bpp时,步幅始终等于宽度*4,这就是代码工作的原因,但在24bpp时,情况并非总是如此

Dim color As Color = color.FromArgb(255, 117, 228, 26)
Dim bmp As Bitmap =
    ImageUtil.CreateSolidcolorBitmap(New Size(2, 2), color, PixelFormat.Format24bppRgb)

Dim pxInfoCol As IEnumerable(Of PixelInfo) = bmp.GetPixelInfo()

For Each pxInfo As PixelInfo In pxInfoCol

    Console.WriteLine(String.Format("Position: {0}, Location: {1}, Color: {2}",
                      pxInfo.Position, pxInfo.Location, pxInfo.Color.ToString))

Next
Position: 0, Location: {X=0,Y=0}, Color: Color [A=255, R=117, G=228, B=26]
Position: 1, Location: {X=1,Y=0}, Color: Color [A=255, R=117, G=228, B=26]
Position: 2, Location: {X=0,Y=1}, Color: Color [A=255, R=26, G=0, B=0]
Position: 3, Location: {X=1,Y=1}, Color: Color [A=255, R=26, G=117, B=228]
Position: 4, Location: {X=0,Y=2}, Color: Color [A=255, R=0, G=117, B=228]
B G R B G R P P B G R B G R P P
B G R B G R B G R B G R B G R B G R B G R B G R