3

複数のキャンバスと多くのボタンを持つ WPF アプリケーションで作業しています。ユーザーは画像を読み込んでボタンの背景を変更できます。

これは、BitmapImage オブジェクトに画像をロードするコードです。

bmp = new BitmapImage();
bmp.BeginInit();
bmp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.UriSource = new Uri(relativeUri, UriKind.Relative);
bmp.EndInit();

EndInit() では、アプリケーションのメモリが非常に大きくなります。

思考を改善する (ただし、問題を実際に解決するわけではありません) ことの 1 つは、追加することです。

bmp.DecodePixelWidth = 1024;

1024 - 私の最大キャンバスサイズ。しかし、幅が 1024 より大きい画像に対してのみこれを行う必要があります。

4

1 に答える 1

5

画像をBitmapFrameに読み込むことで、メタデータを読み取るだけで済むと思います。

private Size GetImageSize(Uri image)
{
    var frame = BitmapFrame.Create(image);
    // You could also look at the .Width and .Height of the frame which 
    // is in 1/96th's of an inch instead of pixels
    return new Size(frame.PixelWidth, frame.PixelHeight);
}

そして、BitmapSource をロードするときに次のことができます。

var img = new Uri(ImagePath);
var size = GetImageSize(img);
var source = new BitmapImage();
source.BeginInit();
if (size.Width > 1024)
    source.DecodePixelWidth = 1024;
source.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
source.CacheOption = BitmapCacheOption.OnLoad;
source.UriSource = new Uri(ImagePath);
source.EndInit();
myImageControl.Source = source;

これを数回テストし、タスク マネージャーでメモリ消費量を調べたところ、その差は大きかった (10MP の写真では、4272 ピクセル幅ではなく 1024 ピクセルでロードすることで、約 40MB のプライベート メモリを節約できた)。

于 2010-09-29T08:33:08.450 に答える