在C#中创建一个空的BitmapSource

9
在C#中创建一个空的(0x0像素或1x1像素且完全透明)BitmapSource实例的最快(几行代码和低资源使用)方法是什么?
6个回答

16

感谢Arcutus的提示,我现在有了这个(运行良好):

var i = BitmapImage.Create(
    2,
    2,
    96,
    96,
    PixelFormats.Indexed1,
    new BitmapPalette(new List<Color> { Colors.Transparent }),
    new byte[] { 0, 0, 0, 0 },
    1);

如果我将这个图像缩小,就会出现ArgumentException异常。我不知道为什么我不能创建一个小于2x2像素的图像。


3
你可以通过使用不同的格式(索引格式更为特殊,但我也不知道确切的原因)来实现。例如:BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgra32, null, new byte[] { 0, 0, 0, 0 }, 4)(在此示例中,步幅为四,因为Bgra32每个像素有四个字节,并且数组中的四个字节描述了一个像素)。编辑:实际上,如果你将字节数组缩短到一个元素以表示一个像素,你的示例也应该可行。 - Alex Paven
使用参数 (1, 1, 96, 96, PixelFormats.Bgra32, null, new byte[] { 0, 0, 0, 0 }, 4) 将防止整个 WPF UI 渲染。 - bitbonk

14
使用Create方法。

以下是从MSDN偷来的示例:)

int width = 128;
int height = width;
int stride = width/8;
byte[] pixels = new byte[height*stride];

// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);

// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
                                         width, height,
                                         96, 96,
                                         PixelFormats.Indexed1,
                                         myPalette, 
                                         pixels, 
                                         stride);

6
使用TransformedBitmap可以创建此类图像而无需分配大型托管字节数组。
var bmptmp = BitmapSource.Create(1,1,96,96,PixelFormats.Bgr24,null,new byte[3]{0,0,0},3);

var imgcreated = new TransformedBitmap(bmptmp, new ScaleTransform(width, height));

3
最简单的BitmapSource可以通过以下方式生成:
    public static BitmapSource CreateEmptyBitmap()
    {
        return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
    }

这将创建一个可见的图像(即黑色像素)。 - bitbonk

3
另一种方法是创建一个继承自BitmapSource的BitmapImage类的实例: BitmapSource emptySource = new BitmapImage(); 将"Original Answer"翻译成"最初的回答"。

1

只需看一下这个。它适用于任何像素格式。

  public static BitmapSource CreateEmtpyBitmapSource(int width, int height, PixelFormat pixelFormat)
    {
        PixelFormat pf = pixelFormat;
        int rawStride = (width * pf.BitsPerPixel + 7) / 8;
        var rawImage = new byte[rawStride * height];
        var bitmap = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, rawStride);
        return bitmap;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接