0

I have an that turns on a webcam and takes a picture of a barcode; this part works fine but I now want to display the picture taken on screen.

I have created the image control in the axml file as follows:

<Image x:Name="BarcodeImage" Margin="5" Height="240" Width="450"/>

As you can see I haven't actually set an image yet as there is nothing to show.

Once the picture has been taken, I save the image to my hard-drive; this works correctly as I can view the image from my PC.

I am then setting the image in code as follows:

this.BarcodeImage.Source = new BitmapImage(new Uri(filename));

This works correctly and I can now see the taken image on the screen.

My problem occurs if I wish to scan a different barcode; I cannot save the next picture taken as the filename already exists so I am trying to delete the picture before saving the next but I keep getting the error message "the file may be in use by another process".

I have tried having a default image that I set to before deleting (hoping that image I want to delete is now not being used), but now both images cannot be deleted (even manually) as they are both being used by another process.

I have also tried setting the image.source to null, but this does not work either.

Do you have any suggestions on how I can delete my image or to clear the current image set?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Grufty
  • 47
  • 6

1 Answers1

1

When you load a BitmapImage directly from a file, the file is locked until the image is released. To avoid that, the easiest way is to load the image from a stream, and to set the CacheOption to OnLoad:

using (var stream = File.OpenRead(filename))
{
    var bmp = new BitmapImage();
    bmp.BeginInit();
    bmp.StreamSource = stream;
    bmp.CacheOption = BitmapCacheOption.OnLoad;
    bmp.EndInit();
    this.BarcodeImage.Source = bmp;
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    It's also necessary to set `bmp.CacheOption = BitmapCacheOption.OnLoad` before calling EndInit and closing the stream. – Clemens Feb 10 '14 at 13:38
  • @Clemens, good point. I edited my answer. – Thomas Levesque Feb 10 '14 at 13:39
  • I was about to respond saying that with this code it just shows a white box but have seen that the code has been edited and with this extra line the code works fine. Thanks for your help. – Grufty Feb 10 '14 at 14:14