简体   繁体   English

如何为画布存储非持久性图像数组以获取背景?

[英]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. 我有一个映像,该映像可以而且必须仅存在于RAM中,并且不能直接来源于我的硬盘或互联网上的任何内容。

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. 大多数为画布对象设置背景图像的教程都要求我创建一个Image对象(Image是抽象的),到目前为止,我发现的唯一子类都具有URI对象,对我而言,这意味着它们引用存在于持久空间中的对象,即远不是我想做的。

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. 有两种方法可以从内存中的数据创建BitmapSource。

Decode a bitmap frame, eg a PNG or JPEG: 解码位图帧,例如PNG或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. 有关详细信息,请参见BitmapSource.Create

Then assign the bitmap to the ImageBrush like this: 然后像这样将位图分配给ImageBrush:

FrameCanvas.Background = new ImageBrush(bitmap);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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