【问题标题】:copy array of byte to array of structure in c#将字节数组复制到c#中的结构数组
【发布时间】:2014-01-02 18:20:02
【问题描述】:

我使用此代码将数据从 bmp 复制到 c# 中的结构数组, 运行程序时显示消息“参数无效”

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);
}

程序出了什么问题,有没有其他方法可以复制,我需要在图片框中显示新的数组?

【问题讨论】:

  • 哪一行在说“参数无效”?我想你有` Bitmap img = new Bitmap(openFileDialog1.FileName);字符串文件名 = openFileDialog1.FileName;` 向后。

标签: c# arrays struct copy picturebox


【解决方案1】:

抱歉,您不能这样使用Array.Copy

你的源数组是byte[],你的目标数组是pix[,]。根据文档 (Array.Copy Method (Array, Int32, Array, Int32, Int32)),数组尺寸必须相同。

sourceArraydestinationArray 参数的维数必须相同。

但即便如此,你也不能使用Array.Copy,因为你真正想做的是将byte[]中的每3个连续项目合并为pix[,]中的一个。不幸的是,使用Array.Copy 是不可能的。

【讨论】:

  • 恐怕你必须使用简单的for循环并一次写一个项目。您不能使用 LINQ,因为无法使用 LINQ 制作二维数组 T[,]
【解决方案2】:

我可以想出几种方法来获取所需的像素信息数组。
最明显的是像

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;
}

但是,您还没有告诉我们您为什么需要这种形式的位图。所以我不能评论这段代码有多合适。有什么理由不能只保留 Bitmap 并根据需要调用 GetPixel 吗?

我不知道您打算拆分多大的图像或需要什么样的性能,但我可以想象嵌套循环在大图像上不会很快。
您可以探索(如有必要)的另一种方法是将数据直接从流中读取为您需要的格式。但是,这需要您了解 .bmp 的文件格式。

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多