When I try to save a BitmapSource that I loaded earlier, a System.IO.IOException
is thrown stating another process is accessing that file and the filestream cannot be opened.
If I only save whithout loading earlier, everything works fine.
The loading code:
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = uri;
if (decodePixelWidth > 0)
image.DecodePixelWidth = decodePixelWidth;
image.EndInit();
the saving code:
using (FileStream fileStream = new FileStream(Directory + "\\" + FileName + ".jpg", FileMode.Create))
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)image));
encoder.QualityLevel = 100;
encoder.Save(fileStream);
}
It seems like after loading the image data, the file is still locked an can never be overwritten while the application who opened it is still running. Any ideas how to solve this? Thanks alot for any solutions.
Inspired by the comments I got on this issue, I solved the problem by reading all bytes into a memorystream and using it as the BitmapImage's Sreamsource.
This one works perfectly:
if (File.Exists(filePath))
{
MemoryStream memoryStream = new MemoryStream();
byte[] fileBytes = File.ReadAllBytes(filePath);
memoryStream.Write(fileBytes, 0, fileBytes.Length);
memoryStream.Position = 0;
image.BeginInit();
image.StreamSource = memoryStream;
if (decodePixelWidth > 0)
image.DecodePixelWidth = decodePixelWidth;
image.EndInit();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With