[英]Wrong output from Marshal.Copy to bitmap
我正在研究PPM
圖像查看器。
我的PPM
文件看起來像這樣,在評論中我解釋了它是如何工作的。
P3
3 2 #widht and heigth
255 #depth, 24bpp in this case
255 0 0 0 255 0 0 0 255 #here, each pixel have 3 values RGB. We have 6 pixels
255 255 0 255 255 255 0 0 0
我讀這個文件是這樣的:通過這段代碼作為byte array
:
var imageWidth = imageStream[1]; // 3
var imageHeight = imageStream[2]; // 2
int j = 0;
var pixels = new byte[imageWidth * imageHeight * 3]; // multiply by 3 channels, R, G, B
for (int i = 4; i < imageStream.Length; i++) //pixel values starts from index 4
{
pixels[j] = (byte)imageStream[i]; // imageStream is array of ints
j++;
}
var bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format24bppRgb);
var bitmapData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
從這段代碼中,我得到計數為18
的pixels
數組。 值如下所示:
255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0, 255, 255, 255, 0, 0, 0
所以它應該是。 IrfanView
像這樣顯示這個圖像:
但是我的程序在將 bitmap 保存到文件后做了這樣的事情:
為什么我從我的代碼中得到錯誤的顏色 output?
至少有兩點不對,
Format24bppRgb
表示 RGB字序,字節序為 BG R。Format24bppRgb
位圖,每行像素的末尾可能會有一些填充。 考慮bitmapData.Stride
來解決這個問題。 Marshal.Copy
無法修復字節交換問題,但可以手動完成,例如(未測試):
unsafe
{
int j = 0;
for (int y = 0; y < imageHeight; y++)
{
byte* ptr = (byte*)bitmapData.Scan0 + bitmapData.Stride * y;
for (int x = 0; x < imageWidth; x++)
{
// R
ptr[2] = pixels[j];
// G
ptr[1] = pixels[j + 1];
// B
ptr[0] = pixels[j + 2];
ptr += 3;
j += 3;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.