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 から高さを設定できますが、塗りつぶされることはありません。ただし、OpacityMask を設定しないとグレーで完全に正しく塗りつぶされ、BitmapImage から直接設定すると正しい OpacityMask で塗りつぶされます。しかし、私が言ったように、私の現実のシナリオでは、データベースからイメージを読み取る必要があるため、この方法では実行できません。

これに関するアイデアはありますか?

4

1 に答える 1

1

問題はimagedata、BitmapFrame が実際にデコードされる前に、作成された MemoryStream が閉じられることです。

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);
}
于 2014-08-14T13:00:02.867 に答える