0

我有一个矩形,我想为其设置一个 OpacityMask。我直接从一个有效的 PNG 图像中尝试了它。但由于我的图像后来来自数据库,我尝试先将 PNG 保存到数组中,然后从中恢复 BitmapImage。这就是我现在所拥有的:

bodenbitmap = new BitmapImage();
bodenbitmap.BeginInit();
bodenbitmap.UriSource = new Uri(@"C:\bla\plan.png", UriKind.Relative);
bodenbitmap.EndInit();


PngBitmapEncoder enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bodenbitmap));
using (MemoryStream ms = new MemoryStream())
{
    enc.Save(ms);
    imagedata = ms.ToArray();
}

ImageSource src = null;
using (MemoryStream ms = new MemoryStream(imagedata))
{
    if (ms != null)
    {
        ms.Seek(0, SeekOrigin.Begin);
        PngBitmapDecoder decoder = new PngBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
        src = decoder.Frames[0];
    }
}

Rectangle rec = new Rectangle();        
rec.OpacityMask = new ImageBrush(src);
rec.Fill = new SolidColorBrush(Colors.Gray);

我可以从矩形的 ImageSource 设置高度和 with,但它永远不会被填充。然而,当我没有设置 OpacityMask 时,它被正确地完全填充为灰色,当我直接从 BitmapImage 设置它时,它被正确的 OpacityMask 填充。但正如我所说,在我的现实世界场景中,我必须从数据库中读取图像,所以我不能这样做。

对此有任何想法吗?

4

1 回答 1

1

问题是从创建的 MemoryStream 在imagedataBitmapFrame 实际解码之前关闭。

您必须将 BitmapCacheOption 从更改BitmapCacheOption.DefaultBitmapCacheOption.OnLoad

using (MemoryStream ms = new MemoryStream(imagedata))
{
    PngBitmapDecoder decoder = new PngBitmapDecoder(
        ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    src = decoder.Frames[0];
}

或更短:

using (var ms = new MemoryStream(imagedata))
{
    src = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
于 2014-08-14T13:00:02.867 回答