I am trying to write a function that converts a BitmapSource to a BitmapImage. The only way I could find to do this was to create a temporary bmp file write and read from the file to create a new BitmapImage. This works fine until you try to delete the file or re-use the function. There are some file handling errors where the file will still be in use until the BitmapImage is freed.
1 - Is there a better way of converting BitmapSource to BitmapImages?
2 - What can I do to return the BitmapImage without freeing it?
public BitmapImage ConvertSourceToBitMapImage(BitmapSource bitmapSource)
{
BitmapImage bmi = null;
try
{
string filePath = @"C:\GitRepository\ReceiptAPP\ReceiptApplication\bin\Debug\testing.bmp";
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(fileStream);
fileStream.Close();
}
Uri path = new Uri(filePath);
bmi = new BitmapImage(path);
File.Delete(filePath);
}
catch(Exception ex)
{
}
return bmi;
}