问题描述
我有一个要为其设置OpacityMask的矩形。我直接从正在运行的PNG图片中进行了尝试。但是由于我的图像后来来自数据库,所以我尝试先将PNG保存到数组中,然后再从中恢复BitmapImage。这就是我现在拥有的:
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);
我可以从ImageSource设置矩形的高度和,但是它永远不会被填充。但是,当我没有设置OpacityMask时,它会完全用灰色完全填充,而当我直接从BitmapImage进行设置时,它会用正确的OpacityMask填充。但是正如我说的那样,在现实世界中,我必须从数据库中读取图像,所以我不能这样做。
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.
对此有任何想法吗?
推荐答案
问题是从 imagedata
创建的MemoryStream在关闭之前
The problem is that the MemoryStream created from imagedata
is closed before the BitmapFrame is actually decoded.
您必须将BitmapCacheOption从 BitmapCacheOption.Default
更改为 BitmapCacheOption.OnLoad
:
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];
}
或更短:
using (var ms = new MemoryStream(imagedata))
{
src = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
这篇关于无法从Byte创建OpacityMask []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!