I'm trying to save a canvas which contains some shapes as image (*.jpg, *.bmp, *.png) and load that image to canvas again.
When I click the "Save button" and then I click the "Load Button" and then I clicked the "Save Button" again, I have the following fault:
The process cannot access the file 'H:\VisualC\HK5\LT Win\ForTesting\TestSaveCanvasToBitmap\bin\Debug\TestImage.bmp' because it is being used by another process.
It seems to be there is a File Stream which is open but isn't closed yet. Can anyone explain for me?
Thanks in advance!
Here is my code
public void SaveImage(Canvas canvas, int width, int height, string filePath)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas);
double dpi = 96d;
RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(canvas);
dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);
BmpBitmapEncoder image = new BmpBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(rtb));
using (Stream fs = File.Create(filePath))
{
image.Save(fs);
fs.Close();
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
int width = (int)myCanvas.ActualWidth;
int height = (int)myCanvas.ActualHeight;
string filePath = "TestImage.bmp";
SaveImage(myCanvas, width, height, filePath);
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(@"TestImage.bmp", UriKind.Relative);
BitmapImage bmi = new BitmapImage(uri);
ImageBrush brush = new ImageBrush();
brush.ImageSource = bmi;
myCanvas.Background = brush;
}