简体   繁体   中英

copy array of byte to array of structure in c#

I use this code to copy data from bmp to array of structure in c#, when run progrom show the message "the parameter is invalid"

struct pix  //structure for pixel in bmp image
{
   public byte b;//Red
   public byte g;//Green
   public byte r;//Blue
};

private void button1_Click(object sender, EventArgs e)
{
   byte[] bmp = File.ReadAllBytes("D:\\x.bmp");
   Bitmap img = new Bitmap(openFileDialog1.FileName);

   pix[,] bmpdata = new pix[img.Height-1, img.Width-1];  
   Array.Copy(bmp, 54, bmpdata, 0, (bmp.Length)-54);
}

what is wrong in program ,is there any other method for copy,and i need to display new array in picturebox ?

Sorry, but you can't use Array.Copy like that.

Your source array is byte[] and your target array is pix[,] . According to documentation ( Array.Copy Method ( Array , Int32 , Array , Int32 , Int32 ) ) arrays dimensions have to be the same.

The sourceArray and destinationArray parameters must have the same number of dimensions.

But even despite of that, you could not use Array.Copy , because what you're really trying to do is merge every 3 consecutive items from byte[] into one within pix[,] . Unfortunately it's not possible using Array.Copy .

I can think of a few ways you could get the array of pixel information you want.
The most obvious would be something like

Bitmap img = new Bitmap(openFileDialog1.FileName);
pix[,] bmpdata = new pix[img.Height-1, img.Width-1];
for (x=0;x<img.Width;x++)
for (y=0;y<img.Height;y++)
{
Color c=img.GetPixel(x,y);
pix[x,y].b=c.B;
pix[x,y].r=c.R;
pix[x,y].g=c.G;
}

You haven't however told us why you want the bitmap in this form. So I can't comment on how suitable this code will be. Is there any reason why you can't just keep the Bitmap and call GetPixel as needed?

I don't know how big the images are that you are intending on taking apart or what sort of performance you need, but I could imagine that nested loop not being fast on a big image.
An alternative that you could explore (if necessary) would be reading the data directly from the stream into the format you need. This however requires you to understand the file format of a .bmp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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