/// <summary>
    /// Initializes the encoder with the provided stream.
    /// </summary>
    /// <param name="stream">The stream to use for initialization.</param>
    /// <param name="cacheOption">The <see cref="BitmapEncoderCacheOption"/> used on initialization.</param>
    public void Initialize(Stream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache)
    {
        DisposeWICStreamProxy();

        _wicStream = _factory.CreateStream(stream);
        Initialize_(_wicStream, cacheOption);
    }
示例#2
0
 public TestApplication(bool headless = false)
     : base(headless)
 {
     using FileStream stream         = File.OpenRead("Screenshot.jpg");
     using var wicFactory            = new IWICImagingFactory();
     using IWICStream? wicStream     = wicFactory.CreateStream(stream);
     using IWICBitmapDecoder decoder = wicFactory.CreateDecoderFromStream(wicStream !);
 }
示例#3
0
        public static void Main()
        {
            var wicFactory = new IWICImagingFactory();

            D2D1.D2D1CreateFactory(FactoryType.SingleThreaded, out ID2D1Factory d2dFactory);

            const string fileName = "output.jpg";
            const int    width    = 512;
            const int    height   = 512;

            var rectangleGeometry = d2dFactory.CreateRoundedRectangleGeometry(new RoundedRectangle(new RectangleF(128, 128, width - 128 * 2, height - 128 * 2), 32, 32));

            var wicBitmap = wicFactory.CreateBitmap(width, height, Vortice.DirectX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);

            var renderTargetProperties = new RenderTargetProperties(new Vortice.DirectX.Direct2D.PixelFormat(Format.Unknown, Vortice.DirectX.Direct2D.AlphaMode.Unknown));

            var d2dRenderTarget = d2dFactory.CreateWicBitmapRenderTarget(wicBitmap, renderTargetProperties);

            var solidColorBrush = d2dRenderTarget.CreateSolidColorBrush(new Color4(1.0f));

            d2dRenderTarget.BeginDraw();
            d2dRenderTarget.Clear(new Color4(0.0f, 0.0f, 0.0f, 1.0f));
            d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
            d2dRenderTarget.EndDraw();

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            using (var stream = wicFactory.CreateStream())
            {
                stream.Initialize(fileName, FileAccess.Write);

                // Initialize a Jpeg encoder with this stream
                using (var encoder = wicFactory.CreateEncoder(ContainerFormat.Jpeg))
                {
                    encoder.Initialize(stream);

                    // Create a Frame encoder
                    var props             = new SharpGen.Runtime.Win32.PropertyBag(IntPtr.Zero);
                    var bitmapFrameEncode = encoder.CreateNewFrame(props);
                    bitmapFrameEncode.Initialize(null);
                    bitmapFrameEncode.SetSize(width, height);
                    var pixelFormatGuid = Vortice.DirectX.WIC.PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
                    bitmapFrameEncode.WriteSource(wicBitmap, null);

                    bitmapFrameEncode.Commit();
                    encoder.Commit();
                }
            }

            using (var app = new TestApplication())
            {
                app.Run();
            }
        }
示例#4
0
        public static void Save(this IWICImagingFactory factory, IWICBitmapSource imageSource, string fileName)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (imageSource == null)
            {
                throw new ArgumentNullException("imageSource");
            }
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            string extension = Path.GetExtension(fileName);

            if (string.IsNullOrEmpty(extension))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "File name '{0}' does not have an extension so encoder type can not be determined.", new object[]
                {
                    fileName
                }));
            }
            Guid encoderId;

            if (extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                encoderId = WicGuids.GUID_ContainerFormatJpeg;
            }
            else if (extension.Equals(".png", StringComparison.OrdinalIgnoreCase))
            {
                encoderId = WicGuids.GUID_ContainerFormatPng;
            }
            else if (extension.Equals(".bmp", StringComparison.OrdinalIgnoreCase))
            {
                encoderId = WicGuids.GUID_ContainerFormatBmp;
            }
            else
            {
                if (!extension.Equals(".tiff", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "File name '{0}' has extension {1} which we can't handle.", new object[]
                    {
                        fileName,
                        extension
                    }));
                }
                encoderId = WicGuids.GUID_ContainerFormatTiff;
            }
            IWICStream iwicstream;

            factory.CreateStream(out iwicstream);
            iwicstream.InitializeFromFilename(fileName, GenericAccess.GENERIC_WRITE);
            factory.Save(imageSource, iwicstream, encoderId);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicstream);
        }
示例#5
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);
             }
         }
 }
示例#6
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);
                }
            }
        }
示例#7
0
        protected override void RunOverride(MainForm form, object tag)
        {
            TempFileCollection    files   = null;
            IWICImagingFactory    factory = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapEncoderInfo info    = null;
            IWICBitmapEncoder     encoder = null;
            IWICStream            stream  = null;
            int i = 0;

            try
            {
                files = new TempFileCollection();
                info  = (IWICBitmapEncoderInfo)factory.CreateComponentInfo(Parent.Clsid);

                do
                {
                    stream.ReleaseComObject();
                    encoder.ReleaseComObject();
                    stream = factory.CreateStream();
                    stream.InitializeFromFilename(files.AddExtension(i.ToString(CultureInfo.InvariantCulture)), NativeMethods.GenericAccessRights.GENERIC_WRITE);
                    i++;
                    try
                    {
                        encoder = info.CreateInstance();
                        encoder.Initialize(stream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);
                    }
                    catch (Exception e)
                    {
                        form.Add(this, e.TargetSite.ToString(Resources._0_Failed), new DataEntry(e));
                        break;
                    }
                }while(ProcessEncoder(form, encoder, tag));
            }
            finally
            {
                factory.ReleaseComObject();
                info.ReleaseComObject();
                encoder.ReleaseComObject();
                stream.ReleaseComObject();
                if (files != null)
                {
                    files.Delete();
                }
            }
        }
示例#8
0
        public static void Save(this IWICImagingFactory factory, IWICBitmapSource imageSource, Stream destinationStream, Guid encoderId)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory");
            }
            if (imageSource == null)
            {
                throw new ArgumentNullException("imageSource");
            }
            if (destinationStream == null)
            {
                throw new ArgumentNullException("destinationStream");
            }
            IWICStream iwicstream;

            factory.CreateStream(out iwicstream);
            iwicstream.InitializeFromIStream(new StreamWrapper(destinationStream));
            factory.Save(imageSource, iwicstream, encoderId);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicstream);
        }
示例#9
0
            private unsafe void SaveScreenshot(string path, ContainerFormat format = ContainerFormat.Jpeg)
            {
                var             d3d11GraphicsDevice = ((D3D11GraphicsDevice)_graphicsDevice !);
                ID3D11Texture2D source = Headless ? d3d11GraphicsDevice !.OffscreenTexture : d3d11GraphicsDevice !.BackBufferTexture;

                using (ID3D11Texture2D staging = d3d11GraphicsDevice !.CaptureTexture(source))
                {
                    staging.DebugName = "STAGING";

                    var textureDesc = staging !.Description;

                    // Determine source format's WIC equivalent
                    Guid pfGuid = default;
                    bool sRGB   = false;
                    switch (textureDesc.Format)
                    {
                    case Vortice.DXGI.Format.R32G32B32A32_Float:
                        pfGuid = WICPixelFormat.Format128bppRGBAFloat;
                        break;

                    //case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break;
                    //case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break;
                    //case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; // DXGI 1.1
                    //case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break;
                    //case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break;
                    //case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break;
                    //case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break;
                    //case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break;
                    //case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break;
                    //case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break;
                    //case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break;

                    case Vortice.DXGI.Format.R8G8B8A8_UNorm:
                        pfGuid = WICPixelFormat.Format32bppRGBA;
                        break;

                    case Vortice.DXGI.Format.R8G8B8A8_UNorm_SRgb:
                        pfGuid = WICPixelFormat.Format32bppRGBA;
                        sRGB   = true;
                        break;

                    case Vortice.DXGI.Format.B8G8R8A8_UNorm:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGRA;
                        break;

                    case Vortice.DXGI.Format.B8G8R8A8_UNorm_SRgb:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGRA;
                        sRGB   = true;
                        break;

                    case Vortice.DXGI.Format.B8G8R8X8_UNorm:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGR;
                        break;

                    case Vortice.DXGI.Format.B8G8R8X8_UNorm_SRgb:     // DXGI 1.1
                        pfGuid = WICPixelFormat.Format32bppBGR;
                        sRGB   = true;
                        break;

                    default:
                        //Console.WriteLine("ERROR: ScreenGrab does not support all DXGI formats (%u). Consider using DirectXTex.\n", static_cast<uint32_t>(desc.Format));
                        return;
                    }

                    // Screenshots don't typically include the alpha channel of the render target
                    Guid targetGuid = default;
                    switch (textureDesc.Format)
                    {
                    case Vortice.DXGI.Format.R32G32B32A32_Float:
                    case Vortice.DXGI.Format.R16G16B16A16_Float:
                        //if (_IsWIC2())
                    {
                        targetGuid = WICPixelFormat.Format96bppRGBFloat;
                    }
                        //else
                        //{
                        //    targetGuid = WICPixelFormat.Format24bppBGR;
                        //}
                        break;

                    case Vortice.DXGI.Format.R16G16B16A16_UNorm:
                        targetGuid = WICPixelFormat.Format48bppBGR;
                        break;

                    case Vortice.DXGI.Format.B5G5R5A1_UNorm:
                        targetGuid = WICPixelFormat.Format16bppBGR555;
                        break;

                    case Vortice.DXGI.Format.B5G6R5_UNorm:
                        targetGuid = WICPixelFormat.Format16bppBGR565;
                        break;

                    case Vortice.DXGI.Format.R32_Float:
                    case Vortice.DXGI.Format.R16_Float:
                    case Vortice.DXGI.Format.R16_UNorm:
                    case Vortice.DXGI.Format.R8_UNorm:
                    case Vortice.DXGI.Format.A8_UNorm:
                        targetGuid = WICPixelFormat.Format8bppGray;
                        break;

                    default:
                        targetGuid = WICPixelFormat.Format24bppBGR;
                        break;
                    }

                    using var wicFactory            = new IWICImagingFactory();
                    using IWICBitmapDecoder decoder = wicFactory.CreateDecoderFromFileName(path);


                    using Stream stream             = File.OpenWrite(path);
                    using IWICStream wicStream      = wicFactory.CreateStream(stream);
                    using IWICBitmapEncoder encoder = wicFactory.CreateEncoder(format, wicStream);
                    // Create a Frame encoder
                    var props = new SharpGen.Runtime.Win32.PropertyBag();
                    var frame = encoder.CreateNewFrame(props);
                    frame.Initialize(props);
                    frame.SetSize(textureDesc.Width, textureDesc.Height);
                    frame.SetResolution(72, 72);
                    frame.SetPixelFormat(targetGuid);

                    var context = d3d11GraphicsDevice !.DeviceContext;
                    //var mapped = context.Map(staging, 0, MapMode.Read, MapFlags.None);
                    Span <Color> colors = context.Map <Color>(staging, 0, 0, MapMode.Read, MapFlags.None);

                    // Check conversion
                    if (targetGuid != pfGuid)
                    {
                        // Conversion required to write
                        using (IWICBitmap bitmapSource = wicFactory.CreateBitmapFromMemory(
                                   textureDesc.Width,
                                   textureDesc.Height,
                                   pfGuid,
                                   colors))
                        {
                            using (IWICFormatConverter formatConverter = wicFactory.CreateFormatConverter())
                            {
                                formatConverter.CanConvert(pfGuid, targetGuid, out RawBool canConvert);
                                if (!canConvert)
                                {
                                    context.Unmap(staging, 0);
                                    return;
                                }

                                formatConverter.Initialize(bitmapSource, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                frame.WriteSource(formatConverter, new Rectangle(textureDesc.Width, textureDesc.Height));
                            }
                        }
                    }
                    else
                    {
                        // No conversion required
                        int stride = WICPixelFormat.GetStride(pfGuid, textureDesc.Width);
                        frame.WritePixels(textureDesc.Height, stride, colors);
                    }

                    context.Unmap(staging, 0);
                    frame.Commit();
                    encoder.Commit();
                }
            }
示例#10
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);
            }
        }
示例#11
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);
            }
        }
示例#12
0
        public static void Main()
        {
            var wicFactory = new IWICImagingFactory();

            D2D1.D2D1CreateFactory(out ID2D1Factory d2dFactory);

            DWrite.DWriteCreateFactory(out IDWriteFactory dwriteFactory).CheckError();
            var textFormat = dwriteFactory.CreateTextFormat("Calibri", 20);

            const string fileName = "output.jpg";
            const int    width    = 512;
            const int    height   = 512;

            var rectangleGeometry = d2dFactory.CreateRoundedRectangleGeometry(new RoundedRectangle(new RectangleF(128, 128, width - 128 * 2, height - 128 * 2), 32, 32));

            var wicBitmap = wicFactory.CreateBitmap(width, height, Vortice.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);

            var renderTargetProperties = new RenderTargetProperties(Vortice.Direct2D1.PixelFormat.Unknown);

            var d2dRenderTarget = d2dFactory.CreateWicBitmapRenderTarget(wicBitmap, renderTargetProperties);

            var solidColorBrush    = d2dRenderTarget.CreateSolidColorBrush(new Color4(1.0f, 1.0f, 1.0f, 1.0f));
            var redSolidColorBrush = d2dRenderTarget.CreateSolidColorBrush(new Color4(1.0f, 0.0f, 0.0f, 1.0f));

            d2dRenderTarget.BeginDraw();
            d2dRenderTarget.Clear(new Color4(0.0f, 0.0f, 0.0f, 1.0f));
            d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
            d2dRenderTarget.DrawText("Hello", textFormat, new Rect(0, 0, 120, 24), redSolidColorBrush);
            d2dRenderTarget.EndDraw();

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            using (var stream = wicFactory.CreateStream(fileName, FileAccess.Write))
            {
                // Initialize a Jpeg encoder with this stream
                using (var encoder = wicFactory.CreateEncoder(ContainerFormat.Jpeg, stream))
                {
                    // Create a Frame encoder
                    var props             = new SharpGen.Runtime.Win32.PropertyBag();
                    var bitmapFrameEncode = encoder.CreateNewFrame(props);
                    bitmapFrameEncode.Initialize(null);
                    bitmapFrameEncode.SetSize(width, height);
                    bitmapFrameEncode.SetPixelFormat(Vortice.WIC.PixelFormat.FormatDontCare);
                    bitmapFrameEncode.WriteSource(wicBitmap);

                    bitmapFrameEncode.Commit();
                    encoder.Commit();
                }
            }

            /*using(var stream = File.OpenRead(fileName))
             * {
             *  GetTextureDimensions(wicFactory, stream);
             * }*/

            using (var app = new TestApplication())
            {
                app.Run();
            }
        }
示例#13
0
        IEnumerable <string> GetDecodableFiles(MainForm form, Guid decoderClsid)
        {
            IWICImagingFactory    factory = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapDecoderInfo info    = null;
            IWICBitmapDecoder     decoder = null;

            try
            {
                info = (IWICBitmapDecoderInfo)factory.CreateComponentInfo(decoderClsid);

                if (Settings.Default.Files != null)
                {
                    foreach (string s in Settings.Default.Files)
                    {
                        IWICStream stream = factory.CreateStream();
                        try
                        {
                            stream.InitializeFromFilename(s, NativeMethods.GenericAccessRights.GENERIC_READ);

                            bool matches = info.MatchesPattern(stream);
                            stream.Seek(0, 0, IntPtr.Zero);
                            decoder = info.CreateInstance();

                            if (decoder != null)
                            {
                                WICBitmapDecoderCapabilities?capabilities = null;

                                try
                                {
                                    capabilities = decoder.QueryCapability(stream);
                                    if (!matches)
                                    {
                                        QueryCapabilitiesError(form, string.Format(CultureInfo.CurrentUICulture, Resources.PatternDoesnotMatchButPassed, "IWICBitmapDecoder::QueryCapability(...)"), new DataEntry(s));
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (Array.IndexOf(queryCapabilitiesErrors, (WinCodecError)Marshal.GetHRForException(e)) < 0)
                                    {
                                        QueryCapabilitiesError(form, e.TargetSite.ToString(Resources._0_FailedWithIncorrectHRESULT), new DataEntry(s), new DataEntry(Resources.Actual, e), new DataEntry(Resources.Expected, queryCapabilitiesErrors));
                                    }
                                }

                                if (capabilities.HasValue && 0 != (uint)(capabilities.Value & (WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanDecodeSomeImages | WICBitmapDecoderCapabilities.WICBitmapDecoderCapabilityCanDecodeAllImages)))
                                {
                                    yield return(s);
                                }
                            }
                        }
                        finally
                        {
                            stream.ReleaseComObject();
                            decoder.ReleaseComObject();
                            decoder = null;
                        }
                    }
                }
            }
            finally
            {
                factory.ReleaseComObject();
                info.ReleaseComObject();
                decoder.ReleaseComObject();
            }
        }
示例#14
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));
            }
        }