简体   繁体   English

字节数组失败时转换位图像素

[英]Converting bitmap pixels as byte array fails

I have to convert the pixels of a bitmap to short array. 我必须将位图的像素转换为短数组。 Therefore I want to: 因此,我想:

  • get the bytes 得到字节
  • convert the bytes to short 转换为短字节

This is my source to get the bytes: 这是我获取字节的来源:

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

This is not returning the expected results. 这没有返回预期的结果。 Is there another way to convert the data? 还有另一种转换数据的方法吗?

Please explain your problem properly. 请正确解释您的问题。 "I'm missing bytes" is not something that can be solved. “我丢失字节”是无法解决的。 What data do you expect, and what do you see? 您期望什么数据,您看到什么?

Bitmap.Save() will return the data according to the specified format, which in all cases contains more than just the pixel data (headers describing width and height, color / palette data, and so on). Bitmap.Save()将根据指定的格式返回数据,在所有情况下,该格式不仅包含像素数据(描述宽度和高度的标题,颜色/调色板数据等)。 If you just want an array of pixel data, you'd better look at Bimap.LockBits() : 如果只需要像素数据数组,则最好查看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);

Now the rgbValues array contains all pixels from the source bitmap, using three bytes per pixel. 现在, rgbValues数组包含源位图中的所有像素,每个像素使用三个字节。 I don't know why you want an array of shorts, but you must be able to figure that out from here. 我不知道为什么要穿短裤,但您必须能够从这里弄清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM