コード例 #1
0
        protected override bool ProcessDecoder(MainForm form, IWICBitmapDecoder decoder, DataEntry[] de, object tag)
        {
            IWICBitmapDecoderInfo info = decoder.GetDecoderInfo();
            try
            {
                Guid clsid;
                info.GetCLSID(out clsid);
                if (clsid != Parent.Clsid)
                {
                    form.Add(this, Resources.IncorrectDecoderPickedUp, de, new DataEntry(Resources.Expected, Parent.Clsid), new DataEntry(Resources.Actual, clsid));
                }
                else
                {
                    Tag t = (Tag)tag;
                    if (!t.SupportsMultiframe && decoder.GetFrameCount() > 1)
                    {
                        form.Add(this, Resources.DecoderDoesNotMultiframe, de, new DataEntry(Resources.FrameCount, decoder.GetFrameCount()));
                    }
                }
            }
            finally
            {
                info.ReleaseComObject();
            }

            return true;
        }
コード例 #2
0
ファイル: BitmapDecoderRule.cs プロジェクト: eakova/resizer
        protected override bool ProcessDecoder(MainForm form, IWICBitmapDecoder decoder, DataEntry[] de, object tag)
        {
            CheckCopyPalette(form, de, decoder.CopyPalette);

            CheckGetColorContexts(form, de, decoder.GetColorContexts);

            if (decoder.GetFrameCount() == 0)
            {
                form.Add(this, Resources.FileNoFrames, de);
            }

            CheckGetBitmapSource(form, de, decoder.GetPreview, WinCodecError.WINCODEC_ERR_UNSUPPORTEDOPERATION);
            CheckGetBitmapSource(form, de, decoder.GetThumbnail, WinCodecError.WINCODEC_ERR_CODECNOTHUMBNAIL);

            return true;
        }
コード例 #3
0
ファイル: PerformanceForm.cs プロジェクト: vbaderks/WICCop
        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();
            }
        }
コード例 #4
0
        public void TestCreateDecoder()
        {
            var factory = GetImagingFactory();

            using (Stream sourceStream = File.Open(@"..\..\..\PanasonicRW2.Tests\P1350577.RW2", FileMode.Open, FileAccess.Read))
            {
                Guid nul    = Guid.Empty;
                var  stream = new StreamComWrapper(sourceStream);
                IWICBitmapDecoder decoder = factory.CreateDecoderFromStream(stream, nul, WICDecodeOptions.WICDecodeMetadataCacheOnDemand);
                decoder.Initialize(stream, WICDecodeOptions.WICDecodeMetadataCacheOnLoad);
                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);
        }
コード例 #5
0
        private static ImageDescription?DecodeMetadata(WICFlags flags, IWICBitmapDecoder decoder, IWICBitmapFrameDecode frame, out Guid pixelFormat)
        {
            var size = frame.Size;

            var metadata = new ImageDescription
            {
                Dimension = TextureDimension.Texture2D,
                Width     = size.Width,
                Height    = size.Height,
                Depth     = 1,
                MipLevels = 1,
                ArraySize = (flags & WICFlags.AllFrames) != 0 ? decoder.FrameCount : 1,
                Format    = DetermineFormat(frame.PixelFormat, flags, out pixelFormat)
            };

            if (metadata.Format == Format.Unknown)
            {
                return(null);
            }

            return(metadata);
        }
コード例 #6
0
ファイル: WicImageContainer.cs プロジェクト: wk-j/PhotoSauce
        public WicGifContainer(IWICBitmapDecoder dec, WicPipelineContext ctx) : base(dec, ctx, FileFormat.Gif)
        {
            using var wicmeta = ComHandle.Wrap(dec.GetMetadataQueryReader());
            var meta = wicmeta.ComObject;

            ScreenWidth  = meta.GetValueOrDefault <ushort>(Wic.Metadata.Gif.LogicalScreenWidth);
            ScreenHeight = meta.GetValueOrDefault <ushort>(Wic.Metadata.Gif.LogicalScreenHeight);

            if (meta.GetValueOrDefault <bool>(Wic.Metadata.Gif.GlobalPaletteFlag))
            {
                using var wicpal = ComHandle.Wrap(Wic.Factory.CreatePalette());
                var pal = wicpal.ComObject;
                dec.CopyPalette(pal);

                uint pcc = pal.GetColorCount();
                uint idx = meta.GetValueOrDefault <byte>(Wic.Metadata.Gif.BackgroundColorIndex);
                if (idx < pcc)
                {
                    var buff = ArrayPool <uint> .Shared.Rent((int)pcc);

                    pal.GetColors(pcc, buff);
                    BackgroundColor = buff[idx];

                    ArrayPool <uint> .Shared.Return(buff);
                }
            }

            var appext = meta.GetValueOrDefault <byte[]>(Wic.Metadata.Gif.AppExtension).AsSpan();

            if (appext.Length == 11 && netscape2_0.SequenceEqual(appext) || animexts1_0.SequenceEqual(appext))
            {
                var appdata = meta.GetValueOrDefault <byte[]>(Wic.Metadata.Gif.AppExtensionData).AsSpan();
                if (appdata.Length >= 4 && appdata[0] >= 3 && appdata[1] == 1)
                {
                    LoopCount = BinaryPrimitives.ReadUInt16LittleEndian(appdata.Slice(2));
                }
            }
        }
コード例 #7
0
        protected override void RunOverride(MainForm form, object tag)
        {
            IWICImagingFactory    factory = (IWICImagingFactory) new WICImagingFactory();
            IWICBitmapDecoderInfo info    = (IWICBitmapDecoderInfo)factory.CreateComponentInfo(Parent.Clsid);
            Guid cf;

            info.GetContainerFormat(out cf);
            IWICBitmapDecoder decoder = null;

            try
            {
                decoder = info.CreateInstance();
                Guid containerFormat;
                try
                {
                    decoder.GetContainerFormat(out containerFormat);
                    if (containerFormat != cf)
                    {
                        form.Add(this, Resources.ContainerFormatsDoNotMatch, new DataEntry(Resources.Actual, cf), new DataEntry(Resources.Expected, containerFormat));
                    }
                }
                catch (Exception e)
                {
                    form.Add(this, e.TargetSite.ToString(Resources._0_Failed), new DataEntry(e));
                }

                ComponentInfoHelper.CheckEquals <IWICBitmapDecoderInfo>(form, decoder.GetDecoderInfo, this, Extensions.CompareInfos);
            }
            finally
            {
                factory.ReleaseComObject();
                info.ReleaseComObject();
                decoder.ReleaseComObject();
            }

            base.RunOverride(form, tag);
        }
コード例 #8
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);
            }
        }
コード例 #9
0
 public extern IWICFastMetadataEncoder CreateFastMetadataEncoderFromDecoder([In, MarshalAs(UnmanagedType.Interface)] IWICBitmapDecoder pIDecoder);
コード例 #10
0
 public static IWICMetadataBlockReader?AsMetadataBlockReader(this IWICBitmapDecoder bitmapDecoder)
 {
     return(bitmapDecoder as IWICMetadataBlockReader);
 }
コード例 #11
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);
        }
コード例 #12
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();
                }
            }
コード例 #13
0
ファイル: DecoderRuleBase.cs プロジェクト: zhaoyingju/resizer
        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
ファイル: DecoderRuleBase.cs プロジェクト: zhaoyingju/resizer
        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));
            }
        }
コード例 #15
0
ファイル: DecoderRuleBase.cs プロジェクト: zhaoyingju/resizer
 protected virtual bool ProcessDecoder(MainForm form, IWICBitmapDecoder decoder, DataEntry[] de, object tag)
 {
     return(true);
 }
コード例 #16
0
ファイル: Image.cs プロジェクト: treytomes/DirectCanvas
        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();
        }
コード例 #17
0
        public static bool TryGetPreview(this IWICBitmapDecoder dec, [NotNullWhen(true)] out IWICBitmapSource?pvw)
        {
            int hr = ProxyFunctions.GetPreview(dec, out pvw);

            return(hr >= 0);
        }
コード例 #18
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);
            }
        }
コード例 #19
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);
        }
コード例 #20
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);
            }
        }
コード例 #21
0
 public static void Initialize(this IWICBitmapDecoder bitmapDecoder, Stream stream, WICDecodeOptions cacheOption)
 {
     bitmapDecoder.Initialize(stream.AsCOMStream(), cacheOption);
 }