問題描述
我嘗試從位圖(System.Drawing.Bitmap)中獲取所有字節(jié)值.因此我鎖定字節(jié)并復制它們:
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 中創(chuàng)建的帶有像素(紅色、綠色、藍色、白色)的非常簡單的 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 格式.有人知道為什么字節(jié)似乎交換了嗎?順便說一句,當我將圖像直接用于 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"/>
推薦答案
像素數(shù)據(jù)為 ARGB,1 字節(jié)為 alpha,1 為紅色,1 為綠色,1 為藍色.Alpha 是最高有效字節(jié),藍色是最低有效字節(jié).在像您和許多其他機器一樣的小端機器上,小端首先存儲,因此字節(jié)順序是 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*(指向整數(shù)的指針)時,此字節(jié)序詳細信息將消失,因為整數(shù)也以小字節(jié)序存儲.
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 似乎有錯誤的字節(jié)順序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!