【问题标题】:Converting bitmap pixels as byte array fails将位图像素转换为字节数组失败
【发布时间】:2012-11-16 03:20:41
【问题描述】:

我必须将位图的像素转换为短数组。因此我想:

  • 获取字节
  • 将字节转换为短字节

这是我获取字节的来源:

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

这没有返回预期的结果。还有其他方法可以转换数据吗?

【问题讨论】:

  • 512 x 512 x 4 = 1048576 那么丢失的字节在哪里?

标签: c# bitmap bytearray converter


【解决方案1】:

请正确解释您的问题。 “我缺少字节” 不是可以解决的。您期望什么数据,您看到了什么?

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 数组包含源位图中的所有像素,每个像素使用三个字节。我不知道你为什么想要一堆短裤,但你必须能够从这里弄清楚。

【讨论】:

猜你喜欢
  • 2013-01-14
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 2018-08-21
  • 1970-01-01
相关资源
最近更新 更多