0

I have an image that can and must only exist in RAM and not be directly derived off of ANYTHING that came from my hard disk or from the internet.

This is because I am testing my own (rather awful) compression functions and must be able to read my own image format. This means that image data must be stored outside persistent memory.

Most tutorials for setting background images for canvas objects require me to create an Image object (Image is abstract) and the only subclasses that I found so far have URI objects, which to me imply that they reference objects that exist in persistent space, which is far from what I want to do.

Ideally, I would like to be able to store, in a non-persistent manner, images that are represented by arrays of pixels, with a width and a length.

public partial class MyClass : Window {
    System.Drawing.Bitmap[] frames;
    int curFrame;
    private void Refresh()
    {
        //FrameCanvas is a simple Canvas object.
        //I wanted to set its background to reflect the data stored
        //in the 
        FrameCanvas.Background = new ImageBrush(frames[curFrame]);
            //this causes an error saying that it can't turn a bitmap
            //to windows.media.imagesource
            //this code won't compile because of that
    }
}
JoseAyeras
  • 75
  • 7
  • 1
    Note that `System.Drawing.Bitmap` is a WinForms class. The equivalent WPF types are BitmapSource and the derived classes BitmapImage and BitmapFrame. – Clemens Apr 01 '19 at 06:15

1 Answers1

1

There are two ways to create a BitmapSource from data in memory.

Decode a bitmap frame, e.g. a PNG or JPEG:

byte[] buffer = ...
BitmapSource bitmap;

using (var memoryStream = new MemoryStream(buffer))
{
    bitmap = BitmapFrame.Create(
        memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

Or create a bitmap from raw pixel data:

PixelFormat format = ...
var stride = (width * format.BitsPerPixel + 7) / 8;

bitmap = BitmapSource.Create(
    width, height,
    dpi, dpi,
    format, null,
    buffer, stride);

See BitmapSource.Create for details.

Then assign the bitmap to the ImageBrush like this:

FrameCanvas.Background = new ImageBrush(bitmap);
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • What's the +7 for btw? Just asking. – JoseAyeras Apr 01 '19 at 17:07
  • It ensures that a stride value is rounded up appropriately, so that a scan line consists of enough bytes to hold all pixel values. See e.g. here: https://stackoverflow.com/a/13953926/1136211. Note that there are PixelFormats with a BitsPerPixel value that is not an integer multiple of 8. – Clemens Apr 01 '19 at 17:14