You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问题:无法将Basler Pylon的IImage.PixelData转换为C# Bitmap

解决Mono8格式像素数据创建Bitmap时的“Parameter is not valid”异常

你遇到的问题核心是:Mono8是裸的单通道8位灰度像素数据,不包含图像文件格式头,而Bitmap(Stream)构造函数只能识别带格式头的数据流(比如BMP、PNG文件流),直接喂原始字节流必然报错。

以下是修正后的代码,直接处理Mono8原始像素数据生成正确的Bitmap:

IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
using (grabResult)
{
    if (grabResult.GrabSucceeded)
    {
        byte[] buffer = grabResult.PixelData as byte[];
        int width = grabResult.Width;
        int height = grabResult.Height;

        // 创建8位索引格式的Bitmap(对应Mono8)
        using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
        {
            // 生成256级灰度调色板,避免默认调色板导致颜色异常
            ColorPalette palette = bmp.Palette;
            for (int i = 0; i < 256; i++)
            {
                palette.Entries[i] = Color.FromArgb(i, i, i);
            }
            bmp.Palette = palette;

            // 锁定Bitmap的像素缓冲区,复制原始数据
            BitmapData bmpData = bmp.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.WriteOnly,
                PixelFormat.Format8bppIndexed);

            // 把Mono8字节数据复制到Bitmap内存
            System.Runtime.InteropServices.Marshal.Copy(
                buffer,
                0,
                bmpData.Scan0,
                buffer.Length);

            bmp.UnlockBits(bmpData);

            // 这里可以使用生成的bmp,比如显示或保存
        }
    }
}

关键说明

  • PixelFormat.Format8bppIndexed:严格匹配Mono8的单通道8位灰度格式,是处理这类数据的正确格式
  • 灰度调色板:默认的8位索引调色板不是灰度渐变,手动生成后才能显示正常的黑白灰度图像
  • LockBits+Marshal.Copy:直接操作内存缓冲区,比逐像素赋值高效得多,适合处理相机采集的大尺寸图像

内容的提问来源于stack exchange,提问作者bougiemane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:47:18