Bitmap Image not changed c#

93 Views Asked by At

I have an area in my wpf project that should display an image by link. The image on the link changes with a certain frequency. My code:

string path1 = @"";//link from image
image_1.Source = null;
GC.Collect();

BitmapImage bi1 = new BitmapImage();
bi1.BeginInit();
bi1.CacheOption = BitmapCacheOption.OnLoad;
bi1.UriSource = new Uri(path1);
bi1.EndInit();
bi1.Freeze();
image_1.Source = bi1;

GC.Collect();
delete_old(path1);//delete file

This all happens in a loop and in the moment between image_1.Source = null and assigning a new value, the image disappears for a while, which looks terrible.

I would like the picture to change from the old to the new one without a blank screen, I did not find other ways to implement it. If I don't set the path to null, then the image just doesn't change.

1

There are 1 best solutions below

0
Vadim Martynov On

Not sure about "clean architecture" solution but there is a workaround that you can use. You can create a 2 Image controls and switch them per each iteration.

At the start you will have 2 controls one visible and one not:

<Grid>
    <Image x:Name="image_1" Stretch="Uniform" />
    <Image x:Name="image_2" Stretch="Uniform" Visibility="Collapsed" />
</Grid>

Now you can modify your code to switch between controls by updating its Visibility:

private Image _currentImage;
private Image _bufferImage;

public YourControlConstructor()
{
    InitializeComponent();

    // initialize a variables with Image controls
    _currentImage = image_1;
    _bufferImage = image_2;
}

private void UpdateImage(string path)
{
    _bufferImage.Source = null;
    GC.Collect();

    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.CacheOption = BitmapCacheOption.OnLoad;
    bi.UriSource = new Uri(path);
    bi.EndInit();
    bi.Freeze();

    _bufferImage.Source = bi;

    // exchange variables to know which image is currently displayed
    Image temp = _currentImage;
    _currentImage = _bufferImage;
    _bufferImage = temp;

    // Update visibility to change images
    _currentImage.Visibility = Visibility.Visible;
    _bufferImage.Visibility = Visibility.Collapsed;

    GC.Collect();
    delete_old(path);
}