0

我有一个可以而且必须只存在于 RAM 中的图像,而不是直接从来自我的硬盘或互联网的任何东西中派生出来的。

这是因为我正在测试我自己的(相当糟糕的)压缩功能,并且必须能够读取我自己的图像格式。这意味着图像数据必须存储在持久内存之外。

大多数为画布对象设置背景图像的教程都要求我创建一个 Image 对象(Image 是抽象的),并且到目前为止我发现的唯一子类具有 URI 对象,这对我来说意味着它们引用存在于持久空间中的对象,即远非我想做的事。

理想情况下,我希望能够以非持久方式存储由像素数组表示的图像,具有宽度和长度。

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

1 回答 1

1

有两种方法可以从内存中的数据创建 BitmapSource。

解码位图帧,例如 PNG 或 JPEG:

byte[] buffer = ...
BitmapSource bitmap;

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

或者从原始像素数据创建位图:

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

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

有关详细信息,请参阅BitmapSource.Create

然后像这样将位图分配给 ImageBrush:

FrameCanvas.Background = new ImageBrush(bitmap);
于 2019-04-01T06:04:49.277 回答