PixelFormat.Format32bppArgb似乎有错误的字节顺序 [英] PixelFormat.Format32bppArgb seems to have wrong byte order

查看:999
本文介绍了PixelFormat.Format32bppArgb似乎有错误的字节顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从一个位图(System.Drawing.Bitmap)获取所有字节值。因此,我锁定字节,并复制它们:

 公共静态的byte []的getPixels(位图位图){
    如果(位图PixelFormat.Equals(PixelFormat.Format32.bppArgb)){
        VAR argbData =新的字节[bitmap.Width * bitmap.Height * 4]。
        变种BD = bitmap.LockBits(新矩形(0,0,image.Width,image.Height),ImageLockMode.ReadOnly,bitmap.PixelFormat);
        System.Runtime.InteropServices.Marshal.Copy(bd.Scan0,argbData,0,bitmap.Width * bitmap.Height * 4);
        bitmap.UnlockBits(BD);
    }
}
 

我测试图像与像素(红,绿,蓝,白),我在Photoshop中创建了一个非常简单的2x2的PNG图片。因为格式的,我期望argbData内的以下数值:

  255 255 0 0 255 0 255 0
255 0 0 255 255 255 255 255
 

不过,我得到了:

  0 0 255 255 0 255 0 255
255 0 0 255 255 255 255 255
 

但是,这是一个BGRA格式。有谁知道为什么字节似乎换? 顺便说一句,当我直接用图像可Image.Source如下图所示,图像显示正确。那么,什么是我的错?

 <图像源=D:/tmp/test2.png/>
 

解决方案

像素数据是ARGB,1字节α,1红,1绿,1蓝色。阿尔法是最显著字节,蓝色是至少显著。在一个小端机,像你和许多人一样,小端存储首次如此字节顺序是BB GG RR AA。所以0 0 255 255等于蓝色= 0,绿色= 0,红= 255,阿尔法= 255这是红色的。

当你施放bd.Scan0到这个字节次序订单的详细信息将消失一个int *(指针到整数),因为整数存储小尾数为好。

I try to get all byte values from a Bitmap(System.Drawing.Bitmap). Therefore I lock the bytes and copy them:

public static byte[] GetPixels(Bitmap bitmap){
    if(bitmap-PixelFormat.Equals(PixelFormat.Format32.bppArgb)){
        var argbData = new byte[bitmap.Width*bitmap.Height*4];
        var bd = bitmap.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
        System.Runtime.InteropServices.Marshal.Copy(bd.Scan0, argbData, 0, bitmap.Width * bitmap.Height * 4);
        bitmap.UnlockBits(bd);
    }
}

I tested this Image with a very simple 2x2 PNG image with pixels (red, green, blue, white) that I created in Photoshop. Because of the format, I expected the following values within the argbData:

255 255   0   0    255 0   255   0 
255 0     0 255    255 255 255 255 

But I got:

0     0 255 255     0 255   0 255
255   0   0 255   255 255 255 255

But this is a BGRA format. Does anybody know why the bytes seems swapped? By the way, when I use the image directly for a Image.Source as shown below, the Image is shown correctly. So what's my fault?

<Image Source="D:/tmp/test2.png"/>

解决方案

Pixel data is ARGB, 1 byte for alpha, 1 for red, 1 for green, 1 for blue. Alpha is the most significant byte, blue is the least significant. On a little-endian machine, like yours and many others, the little end is stored first so the byte order is bb gg rr aa. So 0 0 255 255 equals blue = 0, green = 0, red = 255, alpha = 255. That's red.

This endian-ness order detail disappears when you cast bd.Scan0 to an int* (pointer-to-integer) since integers are stored little-endian as well.

这篇关于PixelFormat.Format32bppArgb似乎有错误的字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆