簡體   English   中英

訪問位圖的字節數組

[英]Access to bytes array of a Bitmap

1-在Windows CE中,我在C#中有一個Bitmap對象。

2-我在extern dll中有一個C函數,該函數期望將指向以RGB565格式,寬度和高度表示的圖像的字節數組的指針作為參數。 此函數將使用此字節數組。

因此,我需要傳遞Bitmap對象的字節數組指針,但是我可以找到一種實用的方法來獲取該指針。 一種方法是使用內存流或其他方法將此位圖轉換為字節數組,但是它將創建一個新的字節數組,因此我將對象,位圖和字節數組都保留在內存中,但我不希望這樣做因為可用內存很少,所以我需要訪問位圖對象的bytes數組,而不是創建新的bytes數組。

有人可以幫助我嗎?

您可以執行以下操作,其中圖像是您的位圖:

Rectangle area = (new Rectangle(0, 0, image.width, image.height));
BtimapData bitmapData = image.LockBits(area, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
stride = bitmapData.Stride;
IntPtr ptr = bitmapData.Scan0;

我知道您不想將位圖的RGB值復制到另一個數組,但這是最好的解決方案。 該數組僅在使用C代碼繪制時才會在內存中。 我在Windows Professional 6中使用了類似的方法,但是並沒有帶來很多開銷。 有許多可用的FastBitmap實現。 您可以在stackoverflow或此實現上檢查此問題

您可以使用不安全的代碼來獲取位圖數據指針。

使用以下代碼:

var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
var bmpData =
    bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
    bmp.PixelFormat);

IntPtr ptr = bmpData.Scan0;

byte* bmpBytes = (byte*)ptr.ToPointer();

其中bmp是您的Bitmap對象。

然后,您也可以執行相反的操作:

ptr = new IntPtr(b);

bmpData.Scan0 = ptr;

多虧了“ NikolaD”和“ oxilumin”的回應,我才能解決我的問題。

當我使用RGB565時,代碼為:

imgMap.Image = new Bitmap(imgMap.Width, imgMap.Height, PixelFormat.Format16bppRgb565);
Rectangle area = (new Rectangle(0, 0, imgMap.Width, imgMap.Height));
BitmapData bitmapData = ((Bitmap)imgMap.Image).LockBits(area, ImageLockMode.ReadWrite, PixelFormat.Format16bppRgb565);
IntPtr ptrImg = bitmapData.Scan0;

其中:imgMap是一個PictureBox

再次感謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM