• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

PixelFormat.Format32bppArgb 似乎有错误的字节顺序

用户头像
it1352
帮助1

问题说明

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

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

我使用在 Photoshop 中创建的带有像素(红色、绿色、蓝色、白色)的非常简单的 2x2 PNG 图像测试了此图像.由于格式的原因,我希望 argbData 中有以下值:

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 

但我得到了:

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

但这是一种 BGRA 格式.有人知道为什么字节似乎交换了吗?顺便说一句,当我将图像直接用于 Image.Source 时,如下所示,图像显示正确.那我的错是什么?

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"/>

正确答案

#1

像素数据为 ARGB,1 字节为 alpha,1 为红色,1 为绿色,1 为蓝色.Alpha 是最高有效字节,蓝色是最低有效字节.在像您和许多其他机器一样的小端机器上,小端首先存储,因此字节顺序是 bb gg rr aa.所以 0 0 255 255 等于蓝色 = 0,绿色 = 0,红色 = 255,alpha = 255.那是红色.

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.

当您将 bd.Scan0 转换为 int*(指向整数的指针)时,此字节序详细信息将消失,因为整数也以小字节序存储.

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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tangicbfg
系列文章
更多 icon
同类精品
更多 icon
继续加载