繁体   English   中英

使用 Visual C# 中由 PixelData 组成的 Byte[] 数组创建位图图像

[英]Creating a BitMap Image out of a Byte[] Array consisting of PixelData in Visual C#

在大学项目中,我和我的团队必须构建一个扫描单元。 扫描单元处理后返回一个由 8 位灰度值组成的字节数组(高度约为 3,7k 像素,宽度约为 20k 像素,这种巨大的分辨率是必要的,因此无法设置 PixelData Pixelwise,因为这将需要很多时间)。

在搜索互联网时,我在这个SO 主题中找到了答案。 我尝试将其实现如下:

public static class Extensions
{
    public static Image ImageFromArray(
    this byte[] arr, int width, int height)
    {
        var output = new Bitmap(width, height, PixelFormat.Format16bppGrayScale);
        var rect = new Rectangle(0, 0, width, height);
        var bmpData = output.LockBits(rect,
            ImageLockMode.ReadWrite, output.PixelFormat);
        var ptr = bmpData.Scan0;
        Marshal.Copy(arr, 0, ptr, arr.Length);
        output.UnlockBits(bmpData);
        return output;
    }
}

我尝试使用这样填充的数组运行函数:

        testarray[0] = 200;
        testarray[1] = 255;
        testarray[2] = 90;
        testarray[3] = 255;
        testarray[4] = 0;
        testarray[5] = 0;
        testarray[6] = 100;
        testarray[7] = 155;

并想在图片框中显示 bmp :

pictureBox1.Image = Extensions.ImageFromArray(testarray, 2, 2);

调试时,代码通过函数运行,但结果是显示错误图像。

此外,如果有人知道一种更简单的计算任务的方法,那么分享方法会非常好。 我找不到方法

  1. 在 C# 中使用 8 位灰度像素格式
  2. 创建一个包含 Stream 和 PixelFormat 的 BitMap 对象

非常感谢您的帮助 :)

  1. 使用 Format8bppIndexed 并设置明显的调色板

    Bitmap ImageFromArray(byte[] arr, int width, int height) { var output = new Bitmap(width, height, PixelFormat.Format8bppIndexed); var rect = new Rectangle(0, 0, width, height); var bmpData = output.LockBits(rect,ImageLockMode.WriteOnly, output.PixelFormat); var ptr = bmpData.Scan0; if (bmpData.Stride != width) throw new InvalidOperationException("Cant copy directly if stride mismatches width, must copy line by line"); Marshal.Copy(arr, 0, ptr, width*height); output.UnlockBits(bmpData); var palEntries = new Color[256]; var cp = output.Palette; for (int i = 0; i < 256; i++) cp.Entries[i] = Color.FromArgb(i, i, i); output.Palette = cp; return output; }
  2. 将 PictureBox.SizeMode 设置为 StretchImage。 你可能需要那个。

暂无
暂无

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

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