无法从Byte []创建OpacityMask

时间:2014-08-14 08:17:03

标签: wpf bytearray bitmapimage opacitymask

我有一个矩形,我想设置一个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设置矩形,但它永远不会被填充。但是,当我没有设置OpacityMask时,它会以灰色正确填充,当我直接从BitmapImage设置它时,它会填充正确的OpacityMask。但正如我所说,在我的真实世界场景中,我必须从数据库中读取图像,所以我不能这样做。

有关于此的任何想法吗?

1 个答案:

答案 0 :(得分:1)

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

您必须将BitmapCacheOption从BitmapCacheOption.Default更改为BitmapCacheOption.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);
}
相关问题