在C#中创建一个空的BitmapSource

bit*_*onk 9 c# wpf bitmapsource

在c#中创建空(0x0 px或1x1 px和完全透明)BitmapSource实例的最快(几行代码和低资源使用)方法是什么,当没有任何应该呈现时使用.

bit*_*onk 13

感谢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);
Run Code Online (Sandbox Code Playgroud)

如果我将这个图像缩小,我会得到一个ArgumentException.我不知道为什么我不能创建一个2x2px的小图像.

  • 你可以使用不同的格式(索引格式更奇特,但我不知道确切的原因).例如:BitmapSource.Create(1,1,96,96,PixelFormats.Bgra32,null,new byte [] {0,0,0,0},4)(在这个例子中,步幅为4,因为有四个Bgra32中每个像素的字节数,并且数组中的四个字节描述了一个像素).编辑:实际上,如果你将字节数组缩短为一个像素的一个元素,我认为你的例子也应该有效. (2认同)

Arc*_*rus 12

使用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);
Run Code Online (Sandbox Code Playgroud)


Ear*_*ine 5

在不分配大型托管字节数组的情况下创建此类图像的方法是使用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));
Run Code Online (Sandbox Code Playgroud)