1

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?

1
  • 2
    512 x 512 x 4 = 1048576 so where is the missing bytes? Commented Nov 28, 2012 at 9:55

1 Answer 1

7

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). If you just want an array of pixel data, you'd better look at 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. I don't know why you want an array of shorts, but you must be able to figure that out from here.

Sign up to request clarification or add additional context in comments.

2 Comments

I have to work with integer values now but in the end there is no difference.thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.