BitmapImage WPF memory issue

I am working on a WPF application that has several canvases and many buttons. User mode loads images to change the button background.

This is the code in which I load the image into a BitmapImage object

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

and in EndInit () application memory grows a lot.

One thing that makes you think better (but doesn't really fix the problem) adds

bmp.DecodePixelWidth = 1024;

1024 is my maximum canvas size. But I should only do this for images with a width greater than 1024 - so how can I get the width before EndInit ()?

+3
source share
1 answer

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

, ( 10- 40 , @1024 4272 )

+5

Source: https://habr.com/ru/post/1767123/


All Articles