• 0

[C#] Image locked during execution


Question

Im currently having a problem managing images in my application.

I'm able to read an image from disk but i also want to be able to replace that image while the program is running...

Problem is though, the image seems to be locked while the program is running and i get an error when i try to replace the file.

			bitImage = new BitmapImage();
			bitImage.BeginInit();
			bitImage.UriSource = new Uri(applicationPath + @"\Scrapbook\" + country + @"\Images\flag.jpg", UriKind.Absolute);
			bitImage.EndInit();

			flagImage.Source = bitImage;

Any way of solving this problem... I saw some exaple converting the image to a stream but couldn't understand how it worked.

Could anyone help....

Thanks

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Are you calling Dispose() on anything? The image file will remain locked until Dispose() is called.

You're right in thinking you should really read it into a stream, that we you kinda decouple the content of the image from the refence to the image:

MemoryStream stream = new MemoryStream();
Bitmap original = Image.FromFile("<path-to-image-file>");
original.Save(stream, ImageFormat.Jpeg);
original.Dispose();

stream.Position = 0;

Edited by Antaris
Link to comment
Share on other sites

  • 0

I had this problem before. You should be able to integrate the basic concept of the code below into your application pretty easily.

using (FileStream imgStrm = new FileStream("C:\\test.jpg", FileMode.Open, FileAccess.Read))
{			
	myPictureBox.Image = Image.FromStream(imgStrm);
}

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.