Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an empty BitmapSource in C#

What is the fastest (few lines of code and low resource usage) way to create an empty (0x0 px or 1x1 px and fully transparent) BitmapSource instance in c# that is used when nothing should be rendered.

like image 210
bitbonk Avatar asked Aug 26 '10 09:08

bitbonk


4 Answers

Just take a look at this. It works for any 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;
    }
like image 97
Andreas Avatar answered Oct 18 '22 21:10

Andreas


Another way is to create an instance of a BitmapImage class which is derived from BitmapSource:

BitmapSource emptySource = new BitmapImage();

like image 29
Lukáš Koten Avatar answered Oct 18 '22 20:10

Lukáš Koten


The most minimal BitmapSource can be generated like this:

    public static BitmapSource CreateEmptyBitmap()
    {
        return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] {0}, 1);
    }
like image 26
michidk Avatar answered Oct 18 '22 20:10

michidk


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);
like image 40
Arcturus Avatar answered Oct 18 '22 19:10

Arcturus