簡體   English   中英

字節數組失敗時轉換位圖像素

[英]Converting bitmap pixels as byte array fails

我必須將位圖的像素轉換為短數組。 因此,我想:

  • 得到字節
  • 轉換為短字節

這是我獲取字節的來源:

 public byte[] BitmapToByte(Bitmap source)
 {
     using (var memoryStream = new MemoryStream())
     {
         source.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
         return memoryStream.ToArray();
     }
 }

這沒有返回預期的結果。 還有另一種轉換數據的方法嗎?

請正確解釋您的問題。 “我丟失字節”是無法解決的。 您期望什么數據,您看到什么?

Bitmap.Save()將根據指定的格式返回數據,在所有情況下,該格式不僅包含像素數據(描述寬度和高度的標題,顏色/調色板數據等)。 如果只需要像素數據數組,則最好查看Bimap.LockBits()

Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");

// Lock the bitmap's bits.  
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);

// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;

// Declare an array to hold the bytes of the bitmap. 
int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];

// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

現在, rgbValues數組包含源位圖中的所有像素,每個像素使用三個字節。 我不知道為什么要穿短褲,但您必須能夠從這里弄清楚。

暫無
暫無

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

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