Question

I have three array of byte stored three colors (Red, Green, Blue), how can I display this array in picture box in c#, and type of file is bitmap file for image

byte[,] R=new byte[width, height];
byte[,] G=new byte[width, height];
byte[,] B=new byte[width, height];

these three array are not empty ,there are data stored in each array.

Was it helpful?

Solution

You mean:

Bitmap bmp = new Bitmap(width,height);
for(int i=0;i<width;i++)
for(int j=0;j<height;j++) {
    SetPixel(i,j,Color.FromArgb(R[i,j],G[i,j],B[i,j]));
}
picturebox.image=bmp;

OTHER TIPS

You have to build a single byte array from the data, which isn't going to be very fast since you have to interleave the data. Basically, you'd do something like this:

var bytes= new byte[width * height * 4];

for (var x = 0; x < width; x++)
  for (var y = 0; y < height; y ++)
  {
    bytes[(x + y * width) * 4 + 1] = R[x, y];
    bytes[(x + y * width) * 4 + 2] = G[x, y];
    bytes[(x + y * width) * 4 + 3] = B[x, y];
  }

And you can then use the byte array to create a bitmap, like this:

var bmp = new Bitmap(width, height);

var data = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

Marshal.Copy(bytes, 0, data.Scan0, width * height * 4);

bmp.UnlockBits(data);

Note that you should ensure that bmp.UnlockBits is always called, so you should probably put it in a finally block.

This isn't necessarily the best or fastest way, but that depends on your needs anyway :)

If you're really going for the fastest way, you'd probably use unsafe code (not because it's faster by itself, but rather because the .NET Bitmap is not natively-managed - it's a managed wrapper for an unmanaged bitmap). You'd allocate the memory for the byte array on the unmanaged heap, then you'd fill in the data and create a bitmap using the constructor that takes an IntPtr scan0 as a parameter. If done correctly, it should avoid unnecessary array boundary checks, as well as unnecessary copying.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top