コード例 #1
0
        public static uint GetColorContextCount(this IWICBitmapFrameDecode frame)
        {
            uint ccc;
            int  hr = GetColorContexts(frame, 0, null, out ccc);

            return(hr >= 0 ? ccc : 0u);
        }
コード例 #2
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);
            }
        }
コード例 #3
0
        public static byte[] WicResize(IWICComponentFactory factory, IWICBitmapFrameDecode frame, int width,
                                       int height, int quality)
        {
            // Prepare output stream to cache file
            var outputStream = new MemoryIStream();
            // Prepare PNG encoder
            var encoder = factory.CreateEncoder(Consts.GUID_ContainerFormatJpeg, null);

            encoder.Initialize(outputStream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);
            // Prepare output frame
            IWICBitmapFrameEncode outputFrame;
            var arg = new IPropertyBag2[1];

            encoder.CreateNewFrame(out outputFrame, arg);
            var propBag           = arg[0];
            var propertyBagOption = new PROPBAG2[1];

            propertyBagOption[0].pstrName = "ImageQuality";
            propBag.Write(1, propertyBagOption, new object[] { ((float)quality) / 100 });
            outputFrame.Initialize(propBag);
            double dpiX, dpiY;

            frame.GetResolution(out dpiX, out dpiY);
            outputFrame.SetResolution(dpiX, dpiY);

            uint ow, oh, w, h;

            frame.GetSize(out ow, out oh);
            if (ow > oh)
            {
                w = (uint)width;
                h = (uint)((double)height * (double)oh / (double)ow);
            }
            else
            {
                w = (uint)((double)height * (double)ow / (double)oh);
                h = (uint)height;
            }


            outputFrame.SetSize(w, h);
            // Prepare scaler
            var scaler = factory.CreateBitmapScaler();

            scaler.Initialize(frame, w, h, WICBitmapInterpolationMode.WICBitmapInterpolationModeFant);
            // Write the scaled source to the output frame
            outputFrame.WriteSource(scaler, new WICRect {
                X = 0, Y = 0, Width = (int)width, Height = (int)height
            });
            outputFrame.Commit();
            encoder.Commit();
            var outputArray = outputStream.ToArray();

            outputStream.Close();
            Marshal.ReleaseComObject(outputFrame);
            Marshal.ReleaseComObject(scaler);
            Marshal.ReleaseComObject(propBag);
            Marshal.ReleaseComObject(encoder);
            return(outputArray);
        }
コード例 #4
0
        public static IWICMetadataQueryReader GetMetadataQueryReaderNoThrow(this IWICBitmapFrameDecode frame)
        {
            IWICMetadataQueryReader rdr;
            int hr = GetMetadataQueryReader(frame, out rdr);

            return(hr >= 0 ? rdr : null);
        }
コード例 #5
0
 public void GetFrame(uint index, out IWICBitmapFrameDecode ppIBitmapFrame)
 {
     Log.Trace($"GetFrame called: {index}");
     try
     {
         if (index != 0)
         {
             throw new COMException("Only 0 Frame available");
         }
         lock (this)
         {
             if (frame == null)
             {
                 frame = new BitmapFrameDecode(stream, exif);
             }
         }
         ppIBitmapFrame = frame;
         Log.Trace("GetFrame finished");
     }
     catch (Exception e)
     {
         Log.Error("GetFrame failed: " + e);
         throw;
     }
 }
コード例 #6
0
        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();
            }
        }
コード例 #7
0
        private void Detect(ImageSource imageSource)
        {
            IWICImagingFactory    iwicimagingFactory    = WicUtility.CreateFactory();
            IWICBitmapFrameDecode iwicbitmapFrameDecode = iwicimagingFactory.Load(imageSource.ImageStream);

            this.DetectSalientRegions(iwicimagingFactory, iwicbitmapFrameDecode);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicbitmapFrameDecode);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicimagingFactory);
        }
コード例 #8
0
        protected ImageBase(Stream stream, Guid wicImageFormat) : this()
        {
            IWICImagingFactory    iwicimagingFactory    = WicUtility.CreateFactory();
            IWICBitmapFrameDecode iwicbitmapFrameDecode = iwicimagingFactory.Load(stream);

            this.LoadFromWic(iwicimagingFactory, iwicbitmapFrameDecode, wicImageFormat);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicimagingFactory);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicbitmapFrameDecode);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: ejohnson-dotnet/heic2jpg
        static void ShowMetadata(IWICBitmapFrameDecode frame)
        {
            var metadataReader = frame.GetMetadataQueryReader();

            foreach (var name in metadataReader.GetNamesRecursive())
            {
                var val = metadataReader.GetMetadataByName(name);
                System.Diagnostics.Trace.WriteLine($"{name}: {GetValue(val)}");
            }
        }
コード例 #10
0
ファイル: BitmapManager.cs プロジェクト: sdcb/FlysEngine
        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));
        }
コード例 #11
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);
        }
コード例 #12
0
        protected override bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
        {
            Guid pixelFormat;
            frame.GetPixelFormat(out pixelFormat);

            Tag t = (Tag)tag;
            if (Array.IndexOf(t.PixelFormats, pixelFormat) < 0)
            {
                form.Add(this, Resources.DecoderUnsuportedPixelFormat, de, new DataEntry(Resources.PixelFormat, pixelFormat), new DataEntry(Resources.SupportedPixelFormats, t.PixelFormats));
            }

            return true;
        }
コード例 #13
0
        protected override bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
        {
            frame.GetPixelFormat(out var pixelFormat);

            var t = (Tag)tag;

            if (Array.IndexOf(t.PixelFormats, pixelFormat) < 0)
            {
                form.Add(this, Resources.DecoderUnsuportedPixelFormat, de, new DataEntry(Resources.PixelFormat, pixelFormat), new DataEntry(Resources.SupportedPixelFormats, t.PixelFormats));
            }

            return(true);
        }
コード例 #14
0
ファイル: WicTools.cs プロジェクト: sdcb/FlysEngine
 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);
             }
         }
 }
コード例 #15
0
        public ImageSource(byte[] buffer)
        {
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentException("Image buffer does not contain a valid image to load.", "buffer");
            }
            this.buffer = buffer;
            IWICImagingFactory    iwicimagingFactory    = WicUtility.CreateFactory();
            IWICBitmapFrameDecode iwicbitmapFrameDecode = iwicimagingFactory.Load(this.ImageStream);
            int num;
            int num2;

            iwicbitmapFrameDecode.GetSize(out num, out num2);
            this.Width  = (float)num;
            this.Height = (float)num2;
            IWICMetadataQueryReader iwicmetadataQueryReader = null;

            try
            {
                iwicbitmapFrameDecode.GetMetadataQueryReader(out iwicmetadataQueryReader);
                string   s;
                DateTime value;
                if (iwicmetadataQueryReader.TryGetMetadataProperty("/app1/ifd/exif/subifd:{uint=36867}", out s) && DateTime.TryParseExact(s, "yyyy:MM:dd HH:mm:ss", null, DateTimeStyles.None, out value))
                {
                    this.DateTaken = new DateTime?(value);
                }
            }
            catch (Exception)
            {
            }
            try
            {
                ushort value2;
                if (iwicmetadataQueryReader.TryGetMetadataProperty("/app1/ifd/{ushort=274}", out value2))
                {
                    this.Orientation = ImageSource.TransformOptionsFromUshort(value2);
                }
                else
                {
                    this.Orientation = WICBitmapTransformOptions.WICBitmapTransformRotate0;
                }
            }
            catch (Exception)
            {
            }
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicmetadataQueryReader);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicbitmapFrameDecode);
            GraphicsInteropNativeMethods.SafeReleaseComObject(iwicimagingFactory);
        }
コード例 #16
0
        public static IComObject <IWICMetadataQueryReader> GetMetadataQueryReader(this IWICBitmapFrameDecode frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            frame.GetMetadataQueryReader(out var value).ThrowOnError(false);
            if (value == null)
            {
                return(null);
            }

            return(new ComObject <IWICMetadataQueryReader>(value));
        }
コード例 #17
0
        public static IComObject <IWICBitmapSource> GetThumbnail(this IWICBitmapFrameDecode frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            frame.GetThumbnail(out var value).ThrowOnError(false);
            if (value == null)
            {
                return(null);
            }

            return(new ComObject <IWICBitmapSource>(value));
        }
コード例 #18
0
ファイル: PerformanceForm.cs プロジェクト: zhaoyingju/resizer
        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();
            }
        }
コード例 #19
0
        public void DecodeResizeAndEncode(byte[] fileBytes, long lData, uint width, uint height, Stream writeTo)
        {
            //A list of COM objects to destroy
            List <object> com = new List <object>();

            try {
                //Create the factory
                IWICComponentFactory factory = (IWICComponentFactory) new WICImagingFactory();
                com.Add(factory);

                //Wrap the byte[] with a IWICStream instance
                var streamWrapper = factory.CreateStream();
                streamWrapper.InitializeFromMemory(fileBytes, (uint)lData);
                com.Add(streamWrapper);

                var decoder = factory.CreateDecoderFromStream(streamWrapper, null,
                                                              WICDecodeOptions.WICDecodeMetadataCacheOnLoad);
                com.Add(decoder);

                IWICBitmapFrameDecode frame = decoder.GetFrame(0);
                com.Add(frame);


                var scaler = factory.CreateBitmapScaler();
                scaler.Initialize(frame, width, height, WICBitmapInterpolationMode.WICBitmapInterpolationModeFant);
                com.Add(scaler);


                var outputStream = new MemoryIStream();


                EncodeToStream(factory, scaler, outputStream);

                outputStream.WriteTo(writeTo);
            } finally {
                //Manually cleanup all the com reference counts, aggressively
                while (com.Count > 0)
                {
                    Marshal.ReleaseComObject(com[com.Count - 1]); //In reverse order, so no item is ever deleted out from under another.
                    com.RemoveAt(com.Count - 1);
                }
            }
        }
コード例 #20
0
        public static IWICColorContext[] GetColorContexts(this IWICBitmapFrameDecode bitmapFrameDecode)
        {
            var wic = new WICImagingFactory();

            bitmapFrameDecode.GetColorContexts(0, null, out int length);

            var colorContexts = new IWICColorContext[length];

            if (length > 0)
            {
                for (int i = 0; i < length; i++)
                {
                    colorContexts[i] = wic.CreateColorContext();
                }

                bitmapFrameDecode.GetColorContexts(length, colorContexts, out _);
            }

            return(colorContexts);
        }
コード例 #21
0
        protected override bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
        {
            CheckGetColorContexts(form, de, frame.GetColorContexts);

            CheckGetBitmapSource(form, de, frame.GetThumbnail, WinCodecError.WINCODEC_ERR_CODECNOTHUMBNAIL);

            uint width;
            uint height;

            frame.GetSize(out width, out height);

            Guid pixelFormat;

            frame.GetPixelFormat(out pixelFormat);


            uint stride = (PixelFormatInfoRule.GetBitPerPixel(pixelFormat) * width + 7) / 8;

            byte[]  buffer = new byte[stride * height];
            WICRect rect   = new WICRect();

            rect.Height = (int)Math.Min(height, int.MaxValue);
            rect.Width  = (int)Math.Min(width, int.MaxValue);
            try
            {
                frame.CopyPixels(rect, stride, stride * height, buffer);
                try
                {
                    frame.CopyPixels(null, stride, stride * height, buffer);
                }
                catch (Exception e)
                {
                    form.Add(this, e.TargetSite.ToString(Resources._0_Failed, "NULL"), de, new DataEntry(e));
                }
            }
            catch
            {
            }

            return(true);
        }
コード例 #22
0
ファイル: BitmapDecoderRule.cs プロジェクト: eakova/resizer
        protected override bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
        {
            CheckGetColorContexts(form, de, frame.GetColorContexts);

            CheckGetBitmapSource(form, de, frame.GetThumbnail, WinCodecError.WINCODEC_ERR_CODECNOTHUMBNAIL);

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

            Guid pixelFormat;
            frame.GetPixelFormat(out pixelFormat);

            uint stride = (PixelFormatInfoRule.GetBitPerPixel(pixelFormat) * width + 7) / 8;
            byte[] buffer = new byte[stride * height];
            WICRect rect = new WICRect();
            rect.Height = (int)Math.Min(height, int.MaxValue);
            rect.Width = (int)Math.Min(width, int.MaxValue);
            try
            {
                frame.CopyPixels(rect, stride, stride * height, buffer);
                try
                {
                    frame.CopyPixels(null, stride, stride * height, buffer);
                }
                catch (Exception e)
                {
                    form.Add(this, e.TargetSite.ToString(Resources._0_Failed, "NULL"), de, new DataEntry(e));
                }
            }
            catch
            {
            }

            return true;
        }
コード例 #23
0
        public static uint GetColorContextCount(this IWICBitmapFrameDecode frame)
        {
            int hr = ProxyFunctions.GetColorContexts(frame, 0, null, out uint ccc);

            return(hr >= 0 ? ccc : 0u);
        }
コード例 #24
0
ファイル: Utils.cs プロジェクト: eakova/resizer
        public static byte[] WicResize(IWICComponentFactory factory, IWICBitmapFrameDecode frame, int width,
            int height, int quality)
        {
            // Prepare output stream to cache file
            var outputStream = new MemoryIStream();
            // Prepare PNG encoder
            var encoder = factory.CreateEncoder(Consts.GUID_ContainerFormatJpeg, null);
            encoder.Initialize(outputStream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);
            // Prepare output frame
            IWICBitmapFrameEncode outputFrame;
            var arg = new IPropertyBag2[1];
            encoder.CreateNewFrame(out outputFrame, arg);
            var propBag = arg[0];
            var propertyBagOption = new PROPBAG2[1];
            propertyBagOption[0].pstrName = "ImageQuality";
            propBag.Write(1, propertyBagOption, new object[] {((float) quality)/100});
            outputFrame.Initialize(propBag);
            double dpiX, dpiY;
            frame.GetResolution(out dpiX, out dpiY);
            outputFrame.SetResolution(dpiX, dpiY);

            uint ow, oh, w, h;
            frame.GetSize(out ow, out oh);
            if (ow > oh ) {
                w = (uint)width;
                h = (uint)((double)height * (double)oh / (double)ow);
            } else {
                w = (uint)((double)height * (double)ow / (double)oh);
                h = (uint)height;
            }

            outputFrame.SetSize(w, h);
            // Prepare scaler
            var scaler = factory.CreateBitmapScaler();
            scaler.Initialize(frame, w, h, WICBitmapInterpolationMode.WICBitmapInterpolationModeFant);
            // Write the scaled source to the output frame
            outputFrame.WriteSource(scaler, new WICRect {X = 0, Y = 0, Width = (int) width, Height = (int) height});
            outputFrame.Commit();
            encoder.Commit();
            var outputArray = outputStream.ToArray();
            outputStream.Close();
            Marshal.ReleaseComObject(outputFrame);
            Marshal.ReleaseComObject(scaler);
            Marshal.ReleaseComObject(propBag);
            Marshal.ReleaseComObject(encoder);
            return outputArray;
        }
コード例 #25
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);
            }
        }
コード例 #26
0
 public extern IWICFastMetadataEncoder CreateFastMetadataEncoderFromFrameDecode([In, MarshalAs(UnmanagedType.Interface)] IWICBitmapFrameDecode pIFrameDecoder);
コード例 #27
0
 private extern static int GetColorContexts(IWICBitmapFrameDecode THIS_PTR, uint cCount, IntPtr[] ppIColorContexts, out uint pcActualCount);
コード例 #28
0
 public void GetFrame(uint index, out IWICBitmapFrameDecode ppIBitmapFrame)
 {
     Log.Trace($"GetFrame called: {index}");
     try
     {
         if (index != 0) throw new COMException("Only 0 Frame available");
         lock (this)
         {
             if (frame == null)
                 frame = new BitmapFrameDecode(stream, exif);
         }
         ppIBitmapFrame = frame;
         Log.Trace("GetFrame finished");
     }
     catch (Exception e)
     {
         Log.Error("GetFrame failed: " + e);
         throw;
     }
 }
コード例 #29
0
 private extern static int GetMetadataQueryReader(IWICBitmapFrameDecode THIS_PTR, out IWICMetadataQueryReader ppIMetadataQueryReader);
コード例 #30
0
        public static bool TryGetMetadataQueryReader(this IWICBitmapFrameDecode frame, [NotNullWhen(true)] out IWICMetadataQueryReader?rdr)
        {
            int hr = ProxyFunctions.GetMetadataQueryReader(frame, out rdr);

            return(hr >= 0);
        }
コード例 #31
0
        protected override bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
        {
            IWICBitmapSourceTransform transform = null;

            try
            {
                transform = (IWICBitmapSourceTransform)frame;
            }
            catch (InvalidCastException)
            {
                return(false);
            }

            if (transform == null)
            {
                form.Add(this, string.Format(CultureInfo.CurrentUICulture, Resources._0_NULL, "IWICBitmapFrameDecode::QueryInterface(IID_IWICBitmapSourceTransform, ...)"), de);
            }
            else
            {
                try
                {
                    if (!transform.DoesSupportTransform(WICBitmapTransformOptions.WICBitmapTransformRotate0))
                    {
                        form.Add(this, string.Format(CultureInfo.CurrentUICulture, Resources._0_NotExpectedValue, "IWICBitmapSourceTransform::DoesSupportTransform(WICBitmapTransformRotate0, ...)"), de, new DataEntry(Resources.Actual, "FALSE"), new DataEntry(Resources.Expected, "TRUE"));
                    }
                    uint width;
                    uint height;
                    frame.GetSize(out width, out height);

                    uint widthSaved  = width;
                    uint heightSaved = height;
                    transform.GetClosestSize(ref width, ref height);

                    if (width != widthSaved || height != heightSaved)
                    {
                        form.Add(this, Resources.IWICBitmapSourceTransform_ChangedSize, de, new DataEntry(Resources.Expected, new Size((int)widthSaved, (int)heightSaved)), new DataEntry(Resources.Actual, new Size((int)width, (int)height)));
                    }

                    Guid pixelFormat;
                    frame.GetPixelFormat(out pixelFormat);

                    Guid pixelFormatSaved = pixelFormat;
                    transform.GetClosestPixelFormat(ref pixelFormat);

                    if (pixelFormat != pixelFormatSaved)
                    {
                        form.Add(this, Resources.IWICBitmapSourceTransform_ChangedPixelformat, de, new DataEntry(Resources.Expected, pixelFormatSaved), new DataEntry(Resources.Actual, pixelFormat));
                    }

                    uint stride = (PixelFormatInfoRule.GetBitPerPixel(pixelFormat) * width + 7) / 8;

                    byte[] buffer = new byte[stride * height];
                    try
                    {
                        transform.CopyPixels(null, width, height, null, WICBitmapTransformOptions.WICBitmapTransformRotate0, stride, (uint)buffer.LongLength, buffer);
                    }
                    catch (Exception e)
                    {
                        form.Add(this, e.TargetSite.ToString(Resources._0_Failed, "NULL, uiWidth, uiHeight, NULL, WICBitmapTransformRotate0, ..."), de, new DataEntry(e), new DataEntry("uiWidth", width), new DataEntry("uiHeight", height));
                    }
                }
                finally
                {
                    transform.ReleaseComObject();
                }
            }

            return(true);
        }
コード例 #32
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));
            }
        }
コード例 #33
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);
            }
        }
コード例 #34
0
ファイル: DecoderRuleBase.cs プロジェクト: zhaoyingju/resizer
 protected virtual bool ProcessFrameDecode(MainForm form, IWICBitmapFrameDecode frame, DataEntry[] de, object tag)
 {
     return(true);
 }