1

The problem seems to be already known with the handling of Image(s). I want to read a Image without locking it. Through various other questions (ex. question), I have found various workarounds. Something that works for many is to save the image using a bitmap ex:

         if (new FileInfo(openImageDialog.FileName).Exists) {
               Image tmp = Image.FromFile(openImageDialog.FileName);
               pictureBoxImage.Image = new Bitmap(tmp);
               tmp?.Dispose();
         }

My problem with this is that I want to display a png with transparency, which is clearly lost with a bitmap.

Can someone come to my rescue?

  • Could you please elaborate, what is the issue with "Image.FromStream" approach mentioned at your link? https://stackoverflow.com/questions/6576341/open-image-from-file-then-release-lock/6576383#6576383 – Vyacheslav Benedichuk Sep 08 '22 at 11:52
  • 1
    `pictureBoxImage.Image?.Dispose(); pictureBoxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(openImageDialog.FileName)), true, false);` – Jimi Sep 08 '22 at 12:09

1 Answers1

1

Create your file stream explicitly and use Image.FromStream instead, allowing you to specify FileShare-mode:

using var fs = File.Open(openImageDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
Image tmp = Image.FromStream(fs);

You could allow FileShare.ReadWrite, but that might not be a good idea since things will likely break if someone is concurrently writing to the same file.

I'm not sure what problem you are describing with regards to transparency. .Net Bitmaps support transparency just fine, .bmp files do not, but you can save and load png files using the Bitmap or Image classes. I'm also unsure what transparency has to do with file locking.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • The code from Jimi in the comment helps me. Thanks for pointing out that C# bitmaps can also store transparency. I suspect that in my project another bug is causing the transparency of the image to be lost, as all transparency pixels are replaced with black pixels. But thanks for the answer! – flyingapple123 Sep 09 '22 at 05:36