none
BmpBitmapEncoder lock files on disk after reading Bitmap from file

    Question

  • I have Image Control in xaml file:

    <Image Height="100" Source="file:///c:/imageShape.bmp" Margin="184,288,0,0" Width="100" HorizontalAlignment="Left" Name="image1" VerticalAlignment="Top" />

    I load this xaml file by XamlReader.Load. After that I try to save bitmap into another file:

    System.Windows.Controls.Image imageControl = ....

    BmpBitmapEncoder bmpBitmapEncoder = new BmpBitmapEncoder();

    BitmapFrame bitmapFrame = BitmapFrame.Create(imageControl.Source as BitmapSource);

    bmpBitmapEncoder.Frames.Add(bitmapFrame);

    MemoryStream stream = new MemoryStream();

    using (FileStream fs = File.Create("t:\\out.bmp"))

    {

    bmpBitmapEncoder.Save(fs);

    }

     

    So, after ".Save(fs)"  original bitmap file (c:\imageShape.bmp) is locked and I can't delete it until I close the process. How can I unlock this file?

    Monday, October 16, 2006 7:46 AM

Answers

  • The trick is to change how the image is loaded into memory. By default, the image bits will be lazily loaded. In that case, we're never sure when we've got all the bits out, so we need to retain a lock on the file. To suck all the bits out on load, specify the OnLoad cache option:

    <Image Margin="184,288,0,0" Width="100" HorizontalAlignment="Left" Name="image1" VerticalAlignment="Top" >
      <Image.Source>
       <BitmapImage UriSource="tulip.jpg" CacheOption="OnLoad"/>
      </Image.Source>
     </Image>

    Tuesday, October 17, 2006 12:01 AM

All replies

  • The trick is to change how the image is loaded into memory. By default, the image bits will be lazily loaded. In that case, we're never sure when we've got all the bits out, so we need to retain a lock on the file. To suck all the bits out on load, specify the OnLoad cache option:

    <Image Margin="184,288,0,0" Width="100" HorizontalAlignment="Left" Name="image1" VerticalAlignment="Top" >
      <Image.Source>
       <BitmapImage UriSource="tulip.jpg" CacheOption="OnLoad"/>
      </Image.Source>
     </Image>

    Tuesday, October 17, 2006 12:01 AM
  • Say that Image object is dynalically detached from its parent (so it's not in memory anymore) and that you don't want to use OnLoad, how can be forced the file unlocking?

    I've seen that if you detach the image and delete the file, it fails.
    But if you detach the image, let the dispatcher work for a while and then delete the file, it works.

    What should I do between detaching and deleting the file?

    TIA

    Tuesday, February 20, 2007 12:46 PM