sharpdx / SharpDX-Samples

Official repository for all SharpDX Samples
346 stars 222 forks source link

TextureLoader.LoadBitmap() does not dispose of resources correctly #45

Open LordBenjamin opened 7 years ago

LordBenjamin commented 7 years ago

Calling TextureLoader.LoadBitmap() results in the target file being locked for the lifetime of the process. This is because it does not dispose of the BitmapDecoder or BitmapDecodeFrame objects that it creates.

The code below fixed for me:

    public static BitmapSource LoadBitmap(ImagingFactory factory, string filename) {
        using (var bitmapDecoder = CreateBitmapDecoder(factory, filename)) {
            using (var frame = bitmapDecoder.GetFrame(0)) {
                var formatConverter = new FormatConverter(factory);

                formatConverter.Initialize(
                    frame,
                    PixelFormat.Format32bppPRGBA,
                    BitmapDitherType.None,
                    null,
                    0.0,
                    BitmapPaletteType.Custom);

                return formatConverter;
            }
        }
    }

    private static BitmapDecoder CreateBitmapDecoder(ImagingFactory factory, string filename) {
        return new BitmapDecoder(
            factory,
            filename,
            DecodeOptions.CacheOnDemand);
    }