相关疑难解决方法(0)

从内存中显示RGBA图像

我有一个包含RGBA编码图像的C#字节数组.在WPF中显示此图像的最佳方法是什么?

一种选择是从字节数组创建一个BitmapSource并将其附加到Image控件.但是,创建一个BitmapSource需要一个用于RGBA32的PixelFormat,这在Windows中似乎不可用.

byte[] buffer = new byte[] { 25, 166, 0, 255, 90, 0, 120, 255 };
BitmapSource.Create(2, 1, 96d, 96d, PixelFormats.Bgra32, null, buffer, 4 * 2);
Run Code Online (Sandbox Code Playgroud)

我绝对不想在我的字节数组中交换像素.

c# wpf image-processing

7
推荐指数
1
解决办法
2292
查看次数

在C#中使用原生HBitmap,同时保留alpha通道/透明度

假设我从本机Windows函数中获取HBITMAP对象/句柄.我可以使用Bitmap.FromHbitmap(nativeHBitmap)将其转换为托管位图,但如果原生图像具有透明度信息(alpha通道),则此转换会丢失它.

有关此问题的Stack Overflow有几个问题.使用来自这个问题的第一个答案的信息(如何使用GDI +绘制ARGB位图?),我编写了一段我尝试过的代码并且它有效.

它基本上使用GetObjectBITMAP结构获取本机HBitmap宽度,高度和指向像素数据位置的指针,然后调用托管Bitmap构造函数:

Bitmap managedBitmap = new Bitmap(bitmapStruct.bmWidth, bitmapStruct.bmHeight,
    bitmapStruct.bmWidth * 4, PixelFormat.Format32bppArgb, bitmapStruct.bmBits);
Run Code Online (Sandbox Code Playgroud)

据我所知(请纠正我,如果我错了),这不会将实际像素数据从原生HBitmap复制到托管位图,它只是将托管位图指向本机HBitmap的像素数据.

我不会在另一个图形(DC)或另一个位图上绘制位图,以避免不必要的内存复制,尤其是对于大位图.

我可以简单地将此位图分配给PictureBox控件或Form BackgroundImage属性.它工作正常,使用透明度正确显示位图.

当我不再使用位图时,我确保BackgroundImage属性不再指向位图,并且我同时配置了托管位图和本机HBitmap.

问题:你能告诉我这个推理和代码是否正确.我希望我不会得到一些意想不到的行为或错误.我希望我能正确释放所有内存和对象.

    private void Example()
    {
        IntPtr nativeHBitmap = IntPtr.Zero;

        /* Get the native HBitmap object from a Windows function here */

        // Create the BITMAP structure and get info from our nativeHBitmap
        NativeMethods.BITMAP bitmapStruct = new NativeMethods.BITMAP();
        NativeMethods.GetObjectBitmap(nativeHBitmap, Marshal.SizeOf(bitmapStruct), ref bitmapStruct);

        // Create the managed bitmap using the pointer to …
Run Code Online (Sandbox Code Playgroud)

c# gdi bitmap hbitmap alpha-transparency

3
推荐指数
1
解决办法
6018
查看次数

标签 统计

c# ×2

alpha-transparency ×1

bitmap ×1

gdi ×1

hbitmap ×1

image-processing ×1

wpf ×1