Can not create OpacityMask from Byte[]

我的未来我决定 提交于 2020-01-06 18:03:44

问题


I have a rectange which I want to set an OpacityMask for. I tried it directly from a PNG Image, which was working. But since my image comes from a Database later, I tried saving the PNG into an array first, and then restoring the BitmapImage from it. This is what I have now:

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);

I can set height and with from the ImageSource for the rectangle, but it is never filled. It is however filled correctly completly in gray, when I do not set the OpacityMask, and it is filled with a correct OpacityMask when I set it directly from the BitmapImage. But as I said, in my real world scenario I have to read the Image from a Database, so I can not do it this way.

Any Ideas on this?


回答1:


The problem is that the MemoryStream created from imagedata is closed before the BitmapFrame is actually decoded.

You have to change the BitmapCacheOption from BitmapCacheOption.Default to BitmapCacheOption.OnLoad:

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

or shorter:

using (var ms = new MemoryStream(imagedata))
{
    src = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}


来源:https://stackoverflow.com/questions/25303226/can-not-create-opacitymask-from-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!