简体   繁体   English

如何从二维字节数组创建图像?

[英]How to create an image from a 2-dimensional byte array?

In my project after long process, i got a 2 dimensional byte array from the IR camera. 经过漫长的过程,在我的项目中,我从红外热像仪获得了二维字节阵列。

The byte array holds image in it... 字节数组在其中保存图像...

How to convert that byte array to image in C#.. 如何在C#中将该字节数组转换为图像。

I know that by 我知道

MemoryStream ms = new MemoryStream(byteArray);
System.drawing.Image im = Image.FromStream(ms);

We can pass 1 dimensional array and convert it into image.. 我们可以传递一维数组并将其转换为图像。

If i pass 2 dimensional array as a single dimensional array.. it shows error.. 如果我通过二维数组作为一维数组..它显示错误..

How to rectify it..???? 如何纠正它.. ???? or else how to convert 2 dimensional byte array to image...??? 否则如何将二维字节数组转换为图像... ???

Thank you!! 谢谢!!

If it's a rectangular array (ie a byte[,] ) instead of a jagged array ( byte[][] ) then you may be able to do it pretty simply with some unsafe code. 如果它是一个矩形数组(即byte[,] )而不是锯齿状的数组( byte[][] ),那么您可以使用一些不安全的代码轻松完成此操作。

Have a look at my parallel Mandelbrot set generation code - only the bottom bit is interesting, where it constructs a Bitmap from a palette and a block of data: 看看我的并行Mandelbrot集生成代码 -只是最底层很有趣,它从调色板和数据块构造了一个位图:

byte[] data = query.ToArray();

unsafe
{
    fixed (byte* ptr = data)
    {
        IntPtr scan0 = new IntPtr(ptr);
        Bitmap bitmap = new Bitmap(ImageWidth, ImageHeight, // Image size
                                   ImageWidth, // Scan size
                                   PixelFormat.Format8bppIndexed, scan0);
        ColorPalette palette = bitmap.Palette;
        palette.Entries[0] = Color.Black;
        for (int i=1; i < 256; i++)
        {
            palette.Entries[i] = Color.FromArgb((i*7)%256, (i*7)%256, 255);
        }
        bitmap.Palette = palette;
        // Stuff
    }
}

I don't know whether you can unpin the array after constructing the bitmap - if I were using this for production code I'd look at that more closely. 我不知道在构造位图后是否可以取消固定数组-如果我将其用于生产代码,我会仔细研究一下。

If you want the byte arrays to be processed inorder, you can do the following 如果要按顺序处理字节数组,则可以执行以下操作

byte[][] doubleArray = GetMyByteArray();
byte[] singleArray = doubleArray.SelectMany(x => x).ToArray();
MemoryStream ms = new MemoryStream(singleArray);
System.drawing.Image im = Image.FromStream(ms);

The SelectMany method essentially takes the arrays of arrays and returns the elements in order. SelectMany方法本质上采用数组数组并按顺序返回元素。 Starting with the first element of the first array, finishing that array and then moving onto the next. 从第一个数组的第一个元素开始,完成该数组,然后移至下一个。 This will continue until all elements are processed. 这将继续,直到处理完所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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