【问题标题】:Bitmap to int[] using Marshal.Copy()位图到 int[] 使用 Marshal.Copy()
【发布时间】:2010-01-04 11:35:24
【问题描述】:

我正在使用Marshal.Copy() 将像素信息从Bitmap 复制到int[] 数组中,问题在于传入该数组的信息全部错误,例如:

             [0] = -8682109; 
             [1] = -8682109; 
             [2] = -8616573; 
             [3] = -8616573; 
             [4] = -8550527; 
             and so on...

方法的代码是:

    private unsafe int[] BmpToBytes_Unsafe(Bitmap bmp)
    {
        BitmapData bData = bmp.LockBits(new Rectangle(new Point(), bmp.Size),
            ImageLockMode.ReadOnly,
            PixelFormat.Format32bppRgb);

        // number of bytes in the bitmap
        byteCount = bData.Stride * (bmp.Height);

        int[] bytes = new int[byteCount / 4];

        Marshal.Copy(bData.Scan0, bytes, 0, byteCount/4);

        // don't forget to unlock the bitmap!!
        bmp.UnlockBits(bData);

        return bytes;

当我使用byte[]数组时,存储的信息是正确的,所以我不知道这里发生了什么。

【问题讨论】:

    标签: c# bitmap marshalling


    【解决方案1】:

    这些值是完全正常的。它们是 32bpp 像素,alpha 通道为 0xff,通常值。换句话说:-8682109 == 0xff7b8583。任何 alpha 值 >= 128 都会使该值变为负数,因为它设置了符号位。

    使用 uint[] 而不是 int[] 可以更容易看到。

    【讨论】:

    • 问题是 Marshal.Copy 方法不使用 uint[],你知道我该如何操作该值,分离 RGB 分量吗?
    • 使用 Color.FromArgb(),它需要一个 int。
    【解决方案2】:

    恕我直言,您的字节数是字节数,现在您将字节除以 4 并期待一组整数,它们实际上是字节。演员没有按照您的意愿进行。

    要将字节数组转换为 int 数组,请使用:

    System.BitConverter.ToInt32(mybyteArray,4);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 2021-11-19
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多