create an empty BitmapSource in C#
Thanks to Arcutus hint I have this now (wich works fine):
var i = BitmapImage.Create(
2,
2,
96,
96,
PixelFormats.Indexed1,
new BitmapPalette(new List<Color> { Colors.Transparent }),
new byte[] { 0, 0, 0, 0 },
1);
If I make this image smaller I get an ArgumentException. I have no clue why I can't create a smaller image that 2x2px.
Use the Create method.
Example stolen from 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);
The way to create such an image without allocating a big managed byte array is to use 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));