【问题标题】:Can not create OpacityMask from Byte[]无法从 Byte[] 创建 OpacityMask
【发布时间】:2014-08-14 08:17:02
【问题描述】:

我有一个矩形,我想为其设置一个 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。但正如我所说,在我的现实世界场景中,我必须从数据库中读取图像,所以我不能这样做。

对此有什么想法吗?

【问题讨论】:

  • 该代码是怎么回事? mybmp 没有在任何地方声明。
  • 我更正了。我尝试直接从图像源设置 OpacityMask,然后从图像源创建了一个新的位图图像,然后将其设置为 OpacityMask,因此源中的对象名称错误。

标签: wpf bytearray bitmapimage opacitymask


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 2017-07-06
    • 2016-01-29
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2015-03-16
    相关资源
    最近更新 更多