【问题标题】:How to load a 16bit (rgb565) bmp into a byte array with c# standard如何使用 c# 标准将 16​​ 位 (rgb565) bmp 加载到字节数组中
【发布时间】:2021-12-27 03:01:47
【问题描述】:

所以我有这段代码,它在我的 windows c# 应用程序或框架 DLL 中运行良好。

        private static Icon? LoadSync(string filepath)
        {
            Stream imageStreamSource = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);

            BmpBitmapDecoder decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            if (bitmapSource.Format != System.Windows.Media.PixelFormats.Bgr565)
            {
                Debug.Print($"Image at path `{filepath}` is not RGB565!");
                return null;
            }

            byte[] icon = new byte[bitmapSource.PixelHeight * bitmapSource.PixelWidth * sizeof(short)];

            bitmapSource.CopyPixels(icon, bitmapSource.PixelWidth * sizeof(short), 0);

            return new Icon() { Width = (ushort)bitmapSource.PixelWidth, Height = (ushort)bitmapSource.PixelHeight, Data = icon };
        }

它将一个 16 位的 .bmp 文件加载到内存中,然后以字节数组的形式将像素提供给我。

然而,我遇到了一个奇怪的编译错误,我的在线搜索似乎发现它是由一个函数在一个实例中声明为扩展方法的方式存在一些奇怪的差异引起的,而在另一个实例中它是一个实际成员。我忘记了细节,但建议的解决方案是从框架切换到标准 dll。我试过了,它解决了我的问题。

但是现在,重新引入上面的代码,我无法再访问System.Windows.Media.Imaging。所以我想知道我必须有哪些选择才能完成同样的事情。

使用普通的旧位图库,数据被转换为(我认为)rgb888,没有任何保留格式的选项。

如果您想知道为什么我需要一个字节数组,我正在将数据发送到带有屏幕的 arduino。

【问题讨论】:

  • 从不知道它有错误。我通常会选择 .net 框架库,但是...它保存的是什么格式?
  • System.Drawing 中支持的 16 位颜色类型为 Rgb565Rgb555Argb1555(作为 little-endian Int16 块)。所以它不应该转换该数据。您可以在图像对象的 PixelFormat 属性上检查这一点。您可以使用LockBitsMarshal.Copy 来获取实际字节。请务必牢记您的 BitmapData 对象的步伐;一行字节的长度不一定等于width * bpp

标签: c# bitmap bmp


【解决方案1】:

我从未完全按照您的要求完成,但我最近确实不得不在一些 C# 代码中处理图像。我添加了 System.Drawing NuGet 包并使用了 Image 类。这可能会有所帮助:https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image?view=windowsdesktop-5.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2010-09-24
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多