在C#中创建一个空的(0x0像素或1x1像素且完全透明)BitmapSource实例的最快(几行代码和低资源使用)方法是什么?
感谢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像素的图像。
以下是从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);
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));
public static BitmapSource CreateEmptyBitmap()
{
return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
}
BitmapSource emptySource = new BitmapImage();
将"Original Answer"翻译成"最初的回答"。只需看一下这个。它适用于任何像素格式。
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;
}
BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgra32, null, new byte[] { 0, 0, 0, 0 }, 4)
(在此示例中,步幅为四,因为Bgra32每个像素有四个字节,并且数组中的四个字节描述了一个像素)。编辑:实际上,如果你将字节数组缩短到一个元素以表示一个像素,你的示例也应该可行。 - Alex Paven