Beispiel #1
0
        public void TestCreateDecoderMultithread()
        {
            var factory = GetImagingFactory();

            using (Stream sourceStream = File.Open(@"..\..\..\PanasonicRW2.Tests\P1350577.RW2", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Guid nul    = Guid.Empty;
                var  stream = new StreamComWrapper(sourceStream);
                IWICBitmapDecoder decoder = factory.CreateDecoderFromStream(stream, nul, WICDecodeOptions.WICDecodeMetadataCacheOnDemand);
                decoder.Initialize(stream, WICDecodeOptions.WICDecodeMetadataCacheOnLoad);
                Parallel.For(0, 8, new ParallelOptions {
                    MaxDegreeOfParallelism = 8
                }, (i) =>
                {
                    IWICBitmapFrameDecode frame;
                    decoder.GetFrame(0, out frame);
                    uint w, h;
                    frame.GetSize(out w, out h);
                    var buf = new byte[w * h * 3];
                    frame.CopyPixels(new WICRect {
                        Height = (int)h, Width = (int)w
                    }, w * 3, (uint)buf.Length, buf);
                });
            }
            Marshal.ReleaseComObject(factory);
        }
Beispiel #2
0
 public static IEnumerable <IWICBitmapFrameDecode> GetFrames(this IWICBitmapDecoder bitmapDecoder)
 {
     for (int i = 0, n = bitmapDecoder.GetFrameCount(); i < n; ++i)
     {
         yield return(bitmapDecoder.GetFrame(i));
     }
 }
Beispiel #3
0
        public static ComObject <IWICBitmapSource> LoadBitmapSource(string filePath, WICDecodeOptions metadataOptions = WICDecodeOptions.WICDecodeMetadataCacheOnDemand)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            var wfac = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapDecoder     decoder = null;
            IWICBitmapFrameDecode frame   = null;

            try
            {
                wfac.CreateDecoderFromFilename(filePath, IntPtr.Zero, (uint)GenericAccessRights.GENERIC_READ, metadataOptions, out decoder).ThrowOnError();
                decoder.GetFrame(0, out frame).ThrowOnError();
                wfac.CreateFormatConverter(out var converter).ThrowOnError();
                var format = WICConstants.GUID_WICPixelFormat32bppPBGRA;
                converter.Initialize(frame, ref format, WICBitmapDitherType.WICBitmapDitherTypeNone, null, 0, WICBitmapPaletteType.WICBitmapPaletteTypeCustom).ThrowOnError();
                return(new ComObject <IWICBitmapSource>(converter));
            }
            finally
            {
                ComObject.Release(frame);
                ComObject.Release(decoder);
                ComObject.Release(wfac);
            }
        }
        static void Main(string[] args)
        {
            IWICImagingFactory    factory         = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapDecoder     decoder         = null;
            IWICBitmapFrameDecode frame           = null;
            IWICFormatConverter   formatConverter = null;

            try
            {
                const string filename = @"<filename>";

                decoder = factory.CreateDecoderFromFilename(filename, null, NativeMethods.GenericAccessRights.GENERIC_READ,
                                                            WICDecodeOptions.WICDecodeMetadataCacheOnDemand);

                uint count = decoder.GetFrameCount();

                frame = decoder.GetFrame(0);

                uint width  = 0;
                uint height = 0;
                frame.GetSize(out width, out height);

                Guid pixelFormat;
                frame.GetPixelFormat(out pixelFormat);

                // The frame can use many different pixel formats.
                // You can copy the raw pixel values by calling "frame.CopyPixels( )".
                // This method needs a buffer that can hold all bytes.
                // The total number of bytes is: width x height x bytes per pixel

                // The disadvantage of this solution is that you have to deal with all possible pixel formats.

                // You can make your life easy by converting the frame to a pixel format of
                // your choice. The code below shows how to convert the pixel format to 24-bit RGB.

                formatConverter = factory.CreateFormatConverter();

                formatConverter.Initialize(frame,
                                           Consts.GUID_WICPixelFormat24bppRGB,
                                           WICBitmapDitherType.WICBitmapDitherTypeNone,
                                           null,
                                           0.0,
                                           WICBitmapPaletteType.WICBitmapPaletteTypeCustom);

                uint   bytesPerPixel = 3; // Because we have converted the frame to 24-bit RGB
                uint   stride        = width * bytesPerPixel;
                byte[] bytes         = new byte[stride * height];

                formatConverter.CopyPixels(null, stride, stride * height, bytes);
            }
            finally
            {
                frame.ReleaseComObject();
                decoder.ReleaseComObject();
                factory.ReleaseComObject();
            }
        }
        public static IComObject <IWICBitmapFrameDecode> GetFrame(this IWICBitmapDecoder decoder, int index)
        {
            if (decoder == null)
            {
                throw new ArgumentNullException(nameof(decoder));
            }

            decoder.GetFrame(index, out var value).ThrowOnError();
            return(new ComObject <IWICBitmapFrameDecode>(value));
        }
Beispiel #6
0
        private static ID2D1Bitmap1 CreateD2dBitmap(
            IWICImagingFactory imagingFactory,
            string filename,
            ID2D1DeviceContext renderTarget)
        {
            using IWICBitmapDecoder decoder   = imagingFactory.CreateDecoderFromFileName(filename);
            using IWICBitmapFrameDecode frame = decoder.GetFrame(0);

            using IWICFormatConverter converter = imagingFactory.CreateFormatConverter();
            converter.Initialize(frame, PixelFormat.Format32bppPBGRA, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);
            return(renderTarget.CreateBitmapFromWicBitmap(converter, null));
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            // This example requires the NuGet package 'stakx.WIC'.
            // https://www.nuget.org/packages/stakx.WIC/
            // https://github.com/stakx/WIC

            const string filename = @"<filename>";

            IWICImagingFactory    factory         = new WICImagingFactory();
            IWICBitmapDecoder     decoder         = null;
            IWICBitmapFrameDecode frame           = null;
            IWICFormatConverter   formatConverter = null;

            decoder = factory.CreateDecoderFromFilename(filename, IntPtr.Zero, StreamAccessMode.GENERIC_READ,
                                                        WICDecodeOptions.WICDecodeMetadataCacheOnDemand);

            int count = decoder.GetFrameCount();

            frame = decoder.GetFrame(0);

            int width  = 0;
            int height = 0;

            frame.GetSize(out width, out height);

            Guid pixelFormat = frame.GetPixelFormat();

            // The frame can use many different pixel formats.
            // You can copy the raw pixel values by calling "frame.CopyPixels( )".
            // This method needs a buffer that can hold all bytes.
            // The total number of bytes is: width x height x bytes per pixel

            // The disadvantage of this solution is that you have to deal with all possible pixel formats.

            // You can make your life easy by converting the frame to a pixel format of
            // your choice. The code below shows how to convert the pixel format to 24-bit RGB.

            formatConverter = factory.CreateFormatConverter();

            formatConverter.Initialize(frame,
                                       GUID_WICPixelFormat24bppRGB,
                                       WICBitmapDitherType.WICBitmapDitherTypeNone,
                                       null,
                                       0.0,
                                       WICBitmapPaletteType.WICBitmapPaletteTypeCustom);

            int bytesPerPixel = 3; // Because we have converted the frame to 24-bit RGB
            int stride        = width * bytesPerPixel;

            byte[] bytes = new byte[stride * height];

            formatConverter.CopyPixels(IntPtr.Zero, stride, stride * height, bytes);
        }
Beispiel #8
0
 public static IWICFormatConverter CreateWicImage(IWICImagingFactory wic, string fileName)
 {
     using (IWICBitmapDecoder decoder = wic.CreateDecoderFromFileName(fileName))
         using (IWICStream decodeStream = wic.CreateStream(fileName, FileAccess.Read))
         {
             decoder.Initialize(decodeStream, DecodeOptions.CacheOnDemand);
             using (IWICBitmapFrameDecode decodeFrame = decoder.GetFrame(0))
             {
                 var converter = wic.CreateFormatConverter();
                 converter.Initialize(decodeFrame, PixelFormat.Format32bppPBGRA, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);
                 return(converter);
             }
         }
 }
Beispiel #9
0
        public static byte[] WicResize(IWICComponentFactory factory, byte[] photoBytes, int width, int height, int quality)
        {
            IWICBitmapDecoder decoder = null;
            var inputStream           = factory.CreateStream();

            try {
                inputStream.InitializeFromMemory(photoBytes, (uint)photoBytes.Length);
                decoder = factory.CreateDecoderFromStream(inputStream, null,
                                                          WICDecodeOptions.WICDecodeMetadataCacheOnLoad);
                return(WicResize(factory, decoder.GetFrame(0), width, height, quality));
            } finally {
                Marshal.ReleaseComObject(decoder);
                Marshal.ReleaseComObject(inputStream);
            }
        }
Beispiel #10
0
    private static WicBitmapSource LoadBitmapSource(Stream stream, int frameIndex, WICDecodeOptions metadataOptions)
    {
        var wfac = (IWICImagingFactory) new WICImagingFactory();
        IWICBitmapDecoder decoder = null;

        try
        {
            decoder = wfac.CreateDecoderFromStream(new ManagedIStream(stream), null, metadataOptions);
            return(new WicBitmapSource(decoder.GetFrame(frameIndex), decoder.GetContainerFormat()));
        }
        finally
        {
            Release(decoder);
            Release(wfac);
        }
    }
Beispiel #11
0
        public static Size GetTextureDimensions(IWICImagingFactory factory, Stream stream)
        {
            IWICStream wicStream = factory.CreateStream();

            wicStream.Initialize(stream);

            using (IWICBitmapDecoder decoder = factory.CreateDecoderFromStream(wicStream, DecodeOptions.CacheOnDemand))
            {
                var frame = decoder.GetFrame(0);
                using (frame)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    return(frame.Size);
                }
            }
        }
Beispiel #12
0
    private static WicBitmapSource LoadBitmapSource(string filePath, int frameIndex, WICDecodeOptions metadataOptions)
    {
        var wfac = (IWICImagingFactory) new WICImagingFactory();
        IWICBitmapDecoder decoder = null;

        try
        {
            decoder = wfac.CreateDecoderFromFilename(filePath, null, GenericAccessRights.GENERIC_READ, metadataOptions);
            return(new WicBitmapSource(decoder.GetFrame(frameIndex), decoder.GetContainerFormat()));
        }
        finally
        {
            Release(decoder);
            Release(wfac);
        }
    }
Beispiel #13
0
        public static IWICBitmapFrameDecode Load(this IWICImagingFactory factory, string fileName)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            IWICBitmapDecoder     iwicbitmapDecoder = factory.CreateDecoderFromFilename(fileName, null, GenericAccess.GENERIC_READ, WICDecodeOptions.WICDecodeMetadataCacheOnDemand);
            IWICBitmapFrameDecode result;

            iwicbitmapDecoder.GetFrame(0, out result);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicbitmapDecoder);
            return(result);
        }
Beispiel #14
0
        public static IWICBitmapFrameDecode Load(this IWICImagingFactory factory, Stream stream)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            StreamWrapper         pIStream          = new StreamWrapper(stream);
            IWICBitmapDecoder     iwicbitmapDecoder = factory.CreateDecoderFromStream(pIStream, null, WICDecodeOptions.WICDecodeMetadataCacheOnDemand);
            IWICBitmapFrameDecode result;

            iwicbitmapDecoder.GetFrame(0, out result);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicbitmapDecoder);
            return(result);
        }
Beispiel #15
0
        private void filesListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (filesListView.SelectedItems.Count > 0)
            {
                string file = filesListView.SelectedItems[0].Text;

                if (decoder != null)
                {
                    decoder.ReleaseComObject();
                    decoder = null;
                }

                if (frame != null)
                {
                    frame.ReleaseComObject();
                    frame = null;
                }

                IWICImagingFactory factory = (IWICImagingFactory) new WICImagingFactory();

                decoder = factory.CreateDecoderFromFilename(file, null, NativeMethods.GenericAccessRights.GENERIC_READ, WICDecodeOptions.WICDecodeMetadataCacheOnLoad);

                if (decoder != null)
                {
                    uint frameCount = decoder.GetFrameCount();

                    if (frameCount > 0)
                    {
                        frame = decoder.GetFrame(0);
                    }

                    if (frame != null)
                    {
                        setupMode = true;
                        SetupDevelopRaw();
                        setupMode = false;

                        DisplayImage();
                    }
                }

                factory.ReleaseComObject();
            }
        }
Beispiel #16
0
        public GifPlayer(string filePath)
        {
            WICImagingFactory factory    = WicImagingFactory = new WICImagingFactory();
            IWICBitmapDecoder gifDecoder = WicBitmapDecoder = factory.CreateDecoderFromFilename(filePath,
                                                                                                null, // Do not prefer a particular vendor
                                                                                                WICDecodeOptions.WICDecodeMetadataCacheOnDemand);
            var wicMetadataQueryReader = gifDecoder.GetMetadataQueryReader();

            GetBackgroundColor(wicMetadataQueryReader);

            var propertyVariant = new PROPVARIANT();

            wicMetadataQueryReader.GetMetadataByName("/logscrdesc/Width", ref propertyVariant);
            if ((propertyVariant.Type & VARTYPE.VT_UI2) == VARTYPE.VT_UI2)
            {
                Width = propertyVariant.Value.UI2;
            }

            // 清空一下
            propertyVariant = new PROPVARIANT();
            wicMetadataQueryReader.GetMetadataByName("/logscrdesc/Height", ref propertyVariant);
            if ((propertyVariant.Type & VARTYPE.VT_UI2) == VARTYPE.VT_UI2)
            {
                Height = propertyVariant.Value.UI2;
            }

            // 清空一下
            propertyVariant = new PROPVARIANT();
            wicMetadataQueryReader.GetMetadataByName("/logscrdesc/PixelAspectRatio", ref propertyVariant);
            if ((propertyVariant.Type & VARTYPE.VT_UI1) == VARTYPE.VT_UI1)
            {
                var pixelAspRatio = propertyVariant.Value.UI2;
                if (pixelAspRatio != 0)
                {
                    // Need to calculate the ratio. The value in uPixelAspRatio
                    // allows specifying widest pixel 4:1 to the tallest pixel of
                    // 1:4 in increments of 1/64th
                    float pixelAspRatioFloat = (pixelAspRatio + 15F) / 64F;
                    // Calculate the image width and height in pixel based on the
                    // pixel aspect ratio. Only shrink the image.

                    if (pixelAspRatioFloat > 1.0F)
                    {
                        WidthGifImagePixel  = Width;
                        HeightGifImagePixel = (ushort)(Height / pixelAspRatioFloat);
                    }
                    else
                    {
                        WidthGifImagePixel  = (ushort)(Width * pixelAspRatioFloat);
                        HeightGifImagePixel = Height;
                    }
                }
                else
                {
                    // The value is 0, so its ratio is 1
                    WidthGifImagePixel  = Width;
                    HeightGifImagePixel = Height;
                }
            }


            var frameCount = gifDecoder.GetFrameCount();

            for (int i = 0; i < frameCount; i++)
            {
                var wicBitmapFrameDecode = gifDecoder.GetFrame(i);
                var wicFormatConverter   = factory.CreateFormatConverter();
                wicFormatConverter.Initialize(wicBitmapFrameDecode, WICPixelFormat.WICPixelFormat24bppBGR, WICBitmapDitherType.WICBitmapDitherTypeNone, null, 0, WICBitmapPaletteType.WICBitmapPaletteTypeCustom);

                const int bytesPerPixel = 3;// BGR 格式
                var       size          = wicFormatConverter.GetSize();
                var       imageByte     = new byte[size.Width * size.Height * bytesPerPixel];
                wicFormatConverter.CopyPixels(24, imageByte);
            }
        }
Beispiel #17
0
        private static SafeHBITMAP _CreateHBITMAPFromImageStream(Stream imgStream, out Size bitmapSize)
        {
            IWICImagingFactory    pImagingFactory = null;
            IWICBitmapDecoder     pDecoder        = null;
            IWICStream            pStream         = null;
            IWICBitmapFrameDecode pDecodedFrame   = null;
            IWICFormatConverter   pBitmapSourceFormatConverter = null;
            IWICBitmapFlipRotator pBitmapFlipRotator           = null;

            SafeHBITMAP hbmp = null;

            try
            {
                using (var istm = new ManagedIStream(imgStream))
                {
                    pImagingFactory = CLSID.CoCreateInstance <IWICImagingFactory>(CLSID.WICImagingFactory);
                    pStream         = pImagingFactory.CreateStream();
                    pStream.InitializeFromIStream(istm);

                    // Create an object that will decode the encoded image
                    Guid vendor = Guid.Empty;
                    pDecoder = pImagingFactory.CreateDecoderFromStream(pStream, ref vendor, WICDecodeMetadata.CacheOnDemand);

                    pDecodedFrame = pDecoder.GetFrame(0);
                    pBitmapSourceFormatConverter = pImagingFactory.CreateFormatConverter();

                    // Convert the image from whatever format it is in to 32bpp premultiplied alpha BGRA
                    Guid pixelFormat = WICPixelFormat.WICPixelFormat32bppPBGRA;
                    pBitmapSourceFormatConverter.Initialize(pDecodedFrame, ref pixelFormat, WICBitmapDitherType.None, IntPtr.Zero, 0, WICBitmapPaletteType.Custom);

                    pBitmapFlipRotator = pImagingFactory.CreateBitmapFlipRotator();
                    pBitmapFlipRotator.Initialize(pBitmapSourceFormatConverter, WICBitmapTransform.FlipVertical);

                    int width, height;
                    pBitmapFlipRotator.GetSize(out width, out height);

                    bitmapSize = new Size {
                        Width = width, Height = height
                    };

                    var bmi = new BITMAPINFO
                    {
                        bmiHeader = new BITMAPINFOHEADER
                        {
                            biSize        = Marshal.SizeOf(typeof(BITMAPINFOHEADER)),
                            biWidth       = width,
                            biHeight      = height,
                            biPlanes      = 1,
                            biBitCount    = 32,
                            biCompression = BI.RGB,
                            biSizeImage   = (width * height * 4),
                        },
                    };

                    // Create a 32bpp DIB.  This DIB must have an alpha channel for UpdateLayeredWindow to succeed.
                    IntPtr pBitmapBits;
                    hbmp = NativeMethods.CreateDIBSection(null, ref bmi, out pBitmapBits, IntPtr.Zero, 0);

                    // Copy the decoded image to the new buffer which backs the HBITMAP
                    var rect = new WICRect {
                        X = 0, Y = 0, Width = width, Height = height
                    };
                    pBitmapFlipRotator.CopyPixels(ref rect, width * 4, bmi.bmiHeader.biSizeImage, pBitmapBits);

                    var ret = hbmp;
                    hbmp = null;
                    return(ret);
                }
            }
            finally
            {
                Utility.SafeRelease(ref pImagingFactory);
                Utility.SafeRelease(ref pDecoder);
                Utility.SafeRelease(ref pStream);
                Utility.SafeRelease(ref pDecodedFrame);
                Utility.SafeRelease(ref pBitmapFlipRotator);
                Utility.SafeRelease(ref pBitmapSourceFormatConverter);
                Utility.SafeDispose(ref hbmp);
            }
        }
Beispiel #18
0
        private T LoadBitmapFromMemory <T>(IntPtr sourceBuffer, uint sourceBufferSize, Guid pixelFormat, CreateBitmapDelegate <T> createBitmap)
        {
            IWICImagingFactory    imagingFactory  = null;
            IWICStream            wicStream       = null;
            IWICBitmapDecoder     decoder         = null;
            IWICBitmapFrameDecode frame           = null;
            IWICFormatConverter   formatConverter = null;

            try
            {
                imagingFactory = new IWICImagingFactory();

                wicStream = imagingFactory.CreateStream();
                wicStream.InitializeFromMemory(sourceBuffer, sourceBufferSize);

                decoder = imagingFactory.CreateDecoderFromStream(
                    wicStream,
                    Guid.Empty,
                    WICDecodeOptions.WICDecodeMetadataCacheOnLoad
                    );

                frame = decoder.GetFrame(0);

                IWICBitmapSource source;

                if (frame.GetPixelFormat() == pixelFormat)
                {
                    source = frame;
                }
                else
                {
                    formatConverter = imagingFactory.CreateFormatConverter();
                    formatConverter.Initialize(
                        frame,
                        WICPixelFormat.GUID_WICPixelFormat32bppPBGRA,
                        WICBitmapDitherType.WICBitmapDitherTypeNone,
                        null,
                        0.0f,
                        WICBitmapPaletteType.WICBitmapPaletteTypeCustom
                        );
                    source = formatConverter;
                }

                source.GetSize(out uint width, out uint height);
                if (width * 4UL > int.MaxValue || height * 4UL > int.MaxValue || 4UL * width * height > int.MaxValue)
                {
                    throw new IOException($"Image is too large: {width}x{height}.");
                }

                WicBitmapSource bitmapSource = new WicBitmapSource(source, (int)width, (int)height);
                return(createBitmap(bitmapSource));
            }
            finally
            {
                SafeRelease(formatConverter);
                SafeRelease(frame);
                SafeRelease(decoder);
                SafeRelease(wicStream);
                SafeRelease(imagingFactory);
            }
        }
Beispiel #19
0
        private static Image DecodeMultiframe(WICFlags flags, ImageDescription metadata, IWICBitmapDecoder decoder)
        {
            var image = Image.New(metadata);

            Guid sourceGuid;

            if (!ToWIC(metadata.Format, out sourceGuid))
            {
                return(null);
            }

            for (var index = 0; index < metadata.ArraySize; ++index)
            {
                var pixelBuffer = image.PixelBuffer[index, 0];

                using (var frame = decoder.GetFrame(index))
                {
                    var pfGuid = frame.PixelFormat;
                    var size   = frame.Size;

                    if (pfGuid == sourceGuid)
                    {
                        if (size.Width == metadata.Width && size.Height == metadata.Height)
                        {
                            // This frame does not need resized or format converted, just copy...
                            frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.BufferStride, pixelBuffer.DataPointer);
                        }
                        else
                        {
                            // This frame needs resizing, but not format converted
                            using (var scaler = Factory.CreateBitmapScaler())
                            {
                                scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags));
                                scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.BufferStride, pixelBuffer.DataPointer);
                            }
                        }
                    }
                    else
                    {
                        // This frame required format conversion
                        using (var converter = Factory.CreateFormatConverter())
                        {
                            converter.Initialize(frame, pfGuid, GetWICDither(flags), null, 0, BitmapPaletteType.Custom);

                            if (size.Width == metadata.Width && size.Height == metadata.Height)
                            {
                                converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.BufferStride, pixelBuffer.DataPointer);
                            }
                            else
                            {
                                // This frame needs resizing, but not format converted
                                using (var scaler = Factory.CreateBitmapScaler())
                                {
                                    scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags));
                                    scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.BufferStride, pixelBuffer.DataPointer);
                                }
                            }
                        }
                    }
                }
            }
            return(image);
        }
Beispiel #20
0
        protected override void RunOverride(MainForm form, object tag)
        {
            bool hasFile   = false;
            bool processed = false;

            IWICImagingFactory    factory = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapDecoderInfo info    = null;
            IWICBitmapDecoder     decoder = null;

            try
            {
                info = (IWICBitmapDecoderInfo)factory.CreateComponentInfo(Parent.Clsid);
                foreach (string file in GetDecodableFiles(form, Parent.Clsid))
                {
                    decoder.ReleaseComObject();
                    decoder = info.CreateInstance();
                    hasFile = true;

                    IWICStream stream = factory.CreateStream();
                    stream.InitializeFromFilename(file, NativeMethods.GenericAccessRights.GENERIC_READ);
                    try
                    {
                        decoder.Initialize(stream, WICDecodeOptions.WICDecodeMetadataCacheOnDemand);

                        if (ProcessDecoder(form, decoder, new DataEntry[] { new DataEntry(file) }, tag))
                        {
                            for (uint index = 0; index < decoder.GetFrameCount(); index++)
                            {
                                IWICBitmapFrameDecode frame = decoder.GetFrame(index);
                                try
                                {
                                    if (ProcessFrameDecode(form, frame, new DataEntry[] { new DataEntry(file), new DataEntry(index) }, tag))
                                    {
                                        processed = true;
                                    }
                                }
                                finally
                                {
                                    frame.ReleaseComObject();
                                }
                            }
                        }
                        else
                        {
                            processed = true;
                        }
                    }
                    catch (Exception e)
                    {
                        form.Add(this, e.TargetSite.ToString(Resources._0_Failed), new DataEntry(file), new DataEntry(e));
                    }
                    finally
                    {
                        stream.ReleaseComObject();
                    }
                }
            }
            finally
            {
                factory.ReleaseComObject();
                info.ReleaseComObject();
                decoder.ReleaseComObject();
            }

            if (!hasFile)
            {
                form.Add(Parent, string.Format(CultureInfo.CurrentUICulture, Resources.NoFilesFor_0, Parent.Text));
            }
            else if (!processed)
            {
                form.Add(this, string.Format(CultureInfo.CurrentUICulture, Resources.NoFilesFor_0, Text));
            }
        }
Beispiel #21
0
        private void Initialize(IWICBitmapDecoder decoder)
        {
            Exception exception = null;

            IWICBitmapFrameDecode source = null;
            IWICFormatConverter converter = null;
            var factory = m_directCanvasFactory.WicImagingFactory;
            int hr = 0;

            hr = decoder.GetFrame(0, out source);

            if (hr != 0)
            {
                exception = new Exception(string.Format("Could not get the frame from the decoder."));
                goto cleanup;
            }

            hr = factory.CreateFormatConverter(out converter);

            if (hr != 0)
            {
                exception = new Exception(string.Format("Could not create the format converter"));
                goto cleanup;
            }

            hr = converter.Initialize(source,
                                      ref WICFormats.WICPixelFormat32bppPBGRA,
                                      WICBitmapDitherType.WICBitmapDitherTypeNone,
                                      null,
                                      0,
                                      WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut);

            if (hr != 0)
            {
                exception = new Exception(string.Format("Could not initialize the converter"));
                goto cleanup;
            }

            bool canConvert;
            hr = converter.CanConvert(ref WICFormats.WICPixelFormat32bppPBGRA,
                                      ref WICFormats.WICPixelFormat32bppBGRA,
                                      out canConvert);

            if (hr != 0)
            {
                exception = new Exception(string.Format("Could not convert color formats"));
                goto cleanup;
            }

            hr = factory.CreateBitmapFromSource(converter,
                                                WICBitmapCreateCacheOption.WICBitmapCacheOnLoad,
                                                out m_internalBitmap);

            if (hr != 0)
            {
                exception = new Exception(string.Format("Could not create bitmap"));
                goto cleanup;
            }

        cleanup:

            if (converter != null)
                Marshal.ReleaseComObject(converter);

            if (source != null)
                Marshal.ReleaseComObject(source);

            if (decoder != null)
                Marshal.ReleaseComObject(decoder);

            if (exception != null)
                throw exception;
            else
                Initialize();
        }
Beispiel #22
0
        internal static Image LoadFromWICMemory(IntPtr pSource, int size, bool makeACopy, GCHandle?handle)
        {
            var flags = WICFlags.AllFrames;

            Image image = null;

            // Create input stream for memory
            using (var stream = Factory.CreateStream(new DataStream(pSource, size, true, false)))
            {
                // If the decoder is unable to decode the image, than return null
                IWICBitmapDecoder decoder = null;
                try
                {
                    decoder = Factory.CreateDecoderFromStream(stream, DecodeOptions.CacheOnDemand);
                    using (var frame = decoder.GetFrame(0))
                    {
                        // Get metadata
                        Guid convertGuid;
                        var  tempDesc = DecodeMetadata(flags, decoder, frame, out convertGuid);

                        // If not supported.
                        if (!tempDesc.HasValue)
                        {
                            return(null);
                        }

                        var mdata = tempDesc.Value;

                        if (mdata.ArraySize > 1 && (flags & WICFlags.AllFrames) != 0)
                        {
                            return(DecodeMultiframe(flags, mdata, decoder));
                        }

                        image = DecodeSingleFrame(flags, mdata, convertGuid, frame);
                    }
                }
                catch
                {
                    image = null;
                }
                finally
                {
                    if (decoder != null)
                    {
                        decoder.Dispose();
                    }
                }
            }

            // For WIC, we are not keeping the original buffer.
            if (image != null && !makeACopy)
            {
                if (handle.HasValue)
                {
                    handle.Value.Free();
                }
                else
                {
                    SdxUtilities.FreeMemory(pSource);
                }
            }
            return(image);
        }