9

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

4

6 回答 6

15

感谢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。我不知道为什么我不能创建一个 2x2px 的较小图像。

于 2010-08-26T11:23:18.003 回答
14

使用创建方法。

从 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);
于 2010-08-26T09:46:12.617 回答
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));
于 2016-02-02T02:09:29.693 回答
3

最小的 BitmapSource 可以这样生成:

    public static BitmapSource CreateEmptyBitmap()
    {
        return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
    }
于 2018-05-13T13:53:06.370 回答
1

看看这个。它适用于任何 Pixelformat

  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;
    }
于 2015-04-17T13:02:33.567 回答
1

另一种方法是创建一个派生自 BitmapSource 的 BitmapImage 类的实例:

BitmapSource emptySource = new BitmapImage();

于 2019-03-05T10:32:07.717 回答