1

For a WPF project I need to read a BitmapImage from a Zip file. The original fileformat is .png I know how to do this directly from a file system and that is working fine. From a Zip file, unfortunately the image is not shown, though an image seems to be read.

I created a simple test project:

public partial class MainWindow : Window
    {

    public BitmapImage RouteImage { get; set; }

    public MainWindow()
        {
        InitializeComponent();
        LoadBitmap();
        DataContext = RouteImage;
        }

    public void LoadBitmap()
        {
        RouteImage = new BitmapImage();
        var PackedFile = @"D:\Temp\MainContent.ap";
        try
            {
                {
                using (ZipArchive archive = ZipFile.OpenRead(PackedFile))
                    {
                    var file = archive.GetEntry("RouteInformation/image.png");
                    if (file != null)
                        {
                        using (var zipEntryStream = file.Open())
                            {
                            RouteImage.BeginInit();
                            RouteImage.CacheOption = BitmapCacheOption.OnLoad;
                            RouteImage.StreamSource = zipEntryStream;
                            RouteImage.EndInit();
                            return;
                            }
                        }
                    }
                }
            }
        catch (Exception e)
            {
            var s = "Exception: " + e.Message;
            }
        }
    }
}

The XAML code looks like this:

<Image Height="128" Width="256"  Source="{Binding BitmapImage}"/>

In the debugger it looks like the stream is created and bound to the BitmapImage, but the width and height are set to 1. so I think something is wrong withe the reading of the data in the zip file.

3
  • 2
    Shouldn't be the Source="{Binding}" since the DataContext is the BitmapImage?
    – S.Toniolo
    Feb 9, 2018 at 8:23
  • First of all. Your Window DataContext is not your BitmapImage. Create a new class as your window DataContext=new yourclass for example, (ViewModel that have to implement inotifypropertychanged interface) and make a property. (This property name should be the same as Binding source name in the xaml part.) After you set your BitmapImage invoke your OnPropertyChanged. Feb 9, 2018 at 8:26
  • Thanks for your fast reply, S.Toniolo I tested, but it does not make any difference. Yes, you can leave out the binding object if it is unambiguous, but seems not to harm using it explicitly. I posted testing code, in real world the class I want to expose has a lot more data to bind. Youstill may be right, I am still quite confused about WPF struggling to learn it.
    – RudolfJan
    Feb 9, 2018 at 8:28

2 Answers 2

2

Not sure about the exact reason, but it seems necessary to copy the zip stream to an intermediate MemoryStream and read the BitmapImage from there.

You should also write a view model class with property change notification:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private BitmapImage routeImage;

    public BitmapImage RouteImage
    {
        get { return routeImage; }
        set
        {
            routeImage = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(RouteImage)));
        }
    }

    public void LoadImage(string archiveName, string entryName)
    {
        using (var archive = ZipFile.OpenRead(archiveName))
        {
            var entry = archive.GetEntry(entryName);
            if (entry != null)
            {
                using (var zipStream = entry.Open())
                using (var memoryStream = new MemoryStream())
                {
                    zipStream.CopyTo(memoryStream); // here
                    memoryStream.Position = 0;

                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource = memoryStream;
                    bitmap.EndInit();

                    RouteImage = bitmap;
                }
            }
        }
    }
}

Assign an instance of the view model to the DataContext of your Window:

public MainWindow()
{
    InitializeComponent();

    var viewModel = new ViewModel();
    DataContext = viewModel;

    viewModel.LoadImage(
        @"D:\Games\steamapps\common\RailWorks\Content\Routes\00000036-0000-0000-0000-000000002012\MainContent.ap",
        "RouteInformation/image.png");
}

and bind the RouteImage property like this:

<Image Source="{Binding RouteImage}"/>

If you are intending to load large image file from the zip archive, I'd recommend to call the view model code in an async method:

public async Task LoadImageAsync(string archiveName, string entryName)
{
    RouteImage = await Task.Run(() => LoadImage(archiveName, entryName));
}

private BitmapImage LoadImage(string archiveName, string entryName)
{
    BitmapImage bitmap = null;

    using (var archive = ZipFile.OpenRead(archiveName))
    {
        var entry = archive.GetEntry(entryName);
        if (entry != null)
        {
            using (var zipStream = entry.Open())
            using (var memoryStream = new MemoryStream())
            {
                zipStream.CopyTo(memoryStream);
                memoryStream.Position = 0;

                bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = memoryStream;
                bitmap.EndInit();
                bitmap.Freeze(); // necessary when loaded in non-UI thread
            }
        }
    }

    return bitmap;
}

Call the method from an async Loaded event handler in your MainWindow:

Loaded += async (s, e) => await viewModel.LoadImageAsync
    @"D:\Games\steamapps\common\RailWorks\Content\Routes\00000036-0000-0000-0000-000000002012\MainContent.ap",
    "RouteInformation/image.png");
2
  • Thank you very much, Clemens! The copy to the memorystream did the trick. PropertyChanged is not needed, because I intend to load the image once in the class constructor. and the images are small. But you gave me a very useful example to work with. :-)
    – RudolfJan
    Feb 9, 2018 at 9:09
  • You're welcome. Sooner or later you'll certainly find the MVVM pattern very useful. I strongly recommend to always implement it, even in simple cases like this.
    – Clemens
    Feb 9, 2018 at 9:10
0

In my work to remove an image from a zip container, that using a middle thread as per Clemens answer only created an exception and was not tenable.

Ultimately I was able to use this code to extract a BitmapImage:

public static class StreamExtensions
{
    public static BitmapImage ToImage(this Stream stream)
    {       
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = stream;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();

        return bitmap;
     }
}

Usage

var image = zipEntry.Open().ToImage();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.