7

I am currently having the following problem: I want to convert a byte array that comes from a file with the following configuration:

Byte1: R color of pixel 0,0.
Byte2: G color of pixel 0,0.
Byte3: B color of pixel 0,0.
Byte4: R color of pixel 0,1.

...
ByteN: R color of pixel n,n.

So what I want to do is convert these bytes into a bitmap without having to set pixel by pixel with bitmap.setPixel because it takes too long.

Any suggestions? Thanks in advance!

hammythepig
  • 947
  • 2
  • 8
  • 30
waclock
  • 185
  • 4
  • 12
  • How are you determined the width / height if all you have is a byte array? Is it a 2-dimensional array? Is it given to you before hand? – vcsjones Jun 07 '12 at 14:29
  • Have you seen this? http://stackoverflow.com/questions/6782489/create-bitmap-from-byte-array-of-pixel-data Bitmap class has a ctor which uses a byte array directly: http://msdn.microsoft.com/en-us/library/zy1a2d14 – kol Jun 07 '12 at 14:30
  • Yes, I do have the width & height of the image. In this case its 1280 x 720. – waclock Jun 07 '12 at 14:30
  • Yes Kol I saw those, I tried with using (MemoryStream stream = new MemoryStream(ArregloBytes)) { Bitmap bmp = new Bitmap(stream); frames.Enqueue(bmp); } – waclock Jun 07 '12 at 14:34
  • But I get an exception saying the argument is not valid. – waclock Jun 07 '12 at 14:34

1 Answers1

11

If you have the byte[] of the pixels, and the width and height, then you can use BitmapData to write the bytes to the bitmap since you also know the format. Here's an example:

//Your actual bytes
byte[] bytes = {255, 0, 0, 0, 0, 255};
var width = 2;
var height = 1;
//Make sure to clean up resources
var bitmap = new Bitmap(width, height);
var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
bitmap.UnlockBits(data);

This is a very fast operation.

You will need to import these three namespaces at the top of your C# file, at minimum:

using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • Thanks for your response, I tried using your code but ImageLockMode, PixelFormat, and Marshal aren't recognized. What extra libraries do I need? – waclock Jun 07 '12 at 14:38