Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to load images into memory?

I have a lot of images in my assets folder of project which i need to load into memory at the start of the app. What is the best way to do it to reduce CPU load and time.

I am doing this:

for (int i = 0; i < 10; i++)
        {
            var smallBitmapImage = new BitmapImage
            {
                UriSource = new Uri(string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i), UriKind.Absolute)
            };

            theme.SmallDigits.Add(new ThemeDigit<BitmapImage> { Value = i, BitmapImage = smallBitmapImage, Image = string.Format("ms-appx:/Assets/Themes/{0}/{1}-small-digit.png", themeName, i) });
        }

And then i bind this BitmapImage to an image control.

But am not exactly sure if setting the UriSource actually loads the image into memory.

I also saw the SetSourceAsync property for BitmapImage. But i am not sure how to use it in my context. Can anyone please help me with either the SetSourceAsync property or the best way to load the images....

Thanks

like image 700
Bitsian Avatar asked Nov 12 '22 15:11

Bitsian


1 Answers

Since I didn't want the wrong answer to be shown I have to add another answer 10 seconds later...

Examples:

BitmapImage image1 = LoadImageToMemory("C:\\image.png");
BitmapImage image2 = LoadImageToMemory(webRequest.GetResponse().GetResponseStream());

public BitmapImage LoadImageToMemory(string path)
{
        BitmapImage image = new BitmapImage();

        try
        {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            System.IO.Stream stream = System.IO.File.Open(path, System.IO.FileMode.Open);
            image.StreamSource = new System.IO.MemoryStream();
            stream.CopyTo(image.StreamSource);
            image.EndInit();

            stream.Close();
            stream.Dispose();
            image.StreamSource.Close();
            image.StreamSource.Dispose();
        }
        catch { throw; }

        return image;
}

// Or to use the System.Net.WebRequest().GetResponse().GetResponseStream()

public BitmapImage LoadImageToMemory(System.IO.Stream stream)
    {
        if (stream.CanRead)
        {
            BitmapImage image = new BitmapImage();

            try
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = new System.IO.MemoryStream();
                stream.CopyTo(image.StreamSource);
                image.EndInit();

                stream.Close();
                stream.Dispose();
                image.StreamSource.Close();
                image.StreamSource.Dispose();
            }
            catch { throw; }

            return image;
        }

        throw new Exception("Cannot read from stream");
}
like image 168
Deukalion Avatar answered Nov 15 '22 04:11

Deukalion