简体   繁体   中英

How do I store a non-persistent array of images for my canvas to get backgrounds from?

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
    }
}

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

Decode a bitmap frame, eg 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM