コード例 #1
0
ファイル: Program.cs プロジェクト: smourier/WicNet
        static void ToTiff(string path)
        {
            using (var bmp = WicBitmapSource.Load(path))
            {
                //Dump(bmp.GetMetadataReader());

                for (var i = 0; i < 8; i++)
                {
                    var option = (WICTiffCompressionOption)i;
                    using var file    = File.OpenWrite("test." + option + ".tiff");
                    using var encoder = WICImagingFactory.CreateEncoder(WicCodec.GUID_ContainerFormatTiff);
                    var mis = new ManagedIStream(file);
                    encoder.Initialize(mis);

                    var newFrame = encoder.CreateNewFrame();

                    var dic = new Dictionary <string, object>();
                    dic["TiffCompressionMethod"] = option;
                    newFrame.Item2.Write(dic);
                    newFrame.Initialize();

                    using (var writer = newFrame.GetMetadataQueryWriter())
                    {
                        //writer.SetMetadataByName("/ifd/{ushort=296}", 1);
                        writer.SetMetadataByName("/ifd/xmp/exif:ImageUniqueID", "ImageId" + option);
                    }

                    newFrame.WriteSource(bmp.ComObject);
                    newFrame.Item1.Commit();

                    encoder.Commit();
                }
            }
        }
コード例 #2
0
 public WicColorContext(object source)
 {
     if (source == null)
     {
         _comObject = WICImagingFactory.CreateColorContext();
     }
     else if (source is IWICColorContext p)
     {
         _comObject = new ComObject <IWICColorContext>(p);
     }
     else if (source is uint colorSpace)
     {
         _comObject = WICImagingFactory.CreateColorContext();
         _comObject.Object.InitializeFromExifColorSpace(colorSpace);
     }
     else if (source is string fileName)
     {
         _comObject = WICImagingFactory.CreateColorContext();
         _comObject.Object.InitializeFromFilename(fileName);
     }
     else if (source is byte[] memory)
     {
         _comObject = WICImagingFactory.CreateColorContext();
         _comObject.Object.InitializeFromMemory(memory, memory.Length);
     }
     else
     {
         _comObject = source as IComObject <IWICColorContext>;
         if (_comObject == null)
         {
             throw new ArgumentException("Source must be an " + nameof(IWICColorContext) + ".", nameof(source));
         }
     }
     _profile = new Lazy <ColorProfile>(() => ColorProfile.FromMemory(ProfileBytes), true);
 }
コード例 #3
0
ファイル: WicPalette.cs プロジェクト: smourier/WicNet
        public WicPalette(object source)
        {
            if (_comObject != null)
            {
                if (source is IWICPalette p)
                {
                    _comObject = new ComObject <IWICPalette>(p);
                }
                else if (source is WicPalette wp)
                {
                    _comObject = WICImagingFactory.CreatePalette();
                    _comObject.Object.InitializeFromPalette(wp._comObject.Object);
                }
                else
                {
                    _comObject = source as IComObject <IWICPalette>;
                    if (_comObject == null)
                    {
                        throw new ArgumentException("Source must be an " + nameof(IWICPalette) + ".", nameof(source));
                    }
                }
            }
            else
            {
                _comObject = WICImagingFactory.CreatePalette();
            }

            _colors = new Lazy <IReadOnlyList <WicColor> >(GetColors, true);
        }
コード例 #4
0
        public static IWICPixelFormatInfo GetPixelFormatInfo(this IWICBitmapSource bitmapSource)
        {
            var  wic             = new WICImagingFactory();
            Guid pixelFormat     = bitmapSource.GetPixelFormat();
            var  pixelFormatInfo = (IWICPixelFormatInfo)wic.CreateComponentInfo(pixelFormat);

            return(pixelFormatInfo);
        }
コード例 #5
0
        public void Rotate(WICBitmapTransformOptions options)
        {
            var clip = WICImagingFactory.CreateBitmapFlipRotator();

            clip.Object.Initialize(_comObject.Object, options).ThrowOnError();
            _comObject?.Dispose();
            _comObject = clip;
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: sbaeumlisberger/WIC-DotNet
        static void Main(string[] args)
        {
            const int width         = 256;
            const int height        = 256;
            const int bytesPerPixel = 3;

            var wif = new WICImagingFactory();

            // find the PNG encoder information
            var pngEncoderInfo = EnumEncoders(wif)
                                 .Where(y => y.GetFriendlyName() == "PNG Encoder")
                                 .First();

            // create the PNG encoder
            var pngEncoder = wif.CreateEncoder(pngEncoderInfo.GetContainerFormat());

            using (var stream = File.Create("result.png"))
            {
                pngEncoder.Initialize(stream.AsCOMStream(), WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);

                var frame = pngEncoder.CreateNewFrame();

                frame.Initialize(null);

                // set pixel format
                var format = WICPixelFormat.WICPixelFormat24bppBGR;
                frame.SetPixelFormat(ref format);

                // check if the pixel format was accepted
                if (format != WICPixelFormat.WICPixelFormat24bppBGR)
                {
                    throw new ArgumentException("The requested pixel format was not accepted");
                }

                frame.SetResolution(new Resolution(96, 96));
                frame.SetSize(width, height);

                var image = new byte[width * height * bytesPerPixel];

                // create a RGB gradient image
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        image[(y * width + x) * bytesPerPixel + 0] = (byte)x;           // blue
                        image[(y * width + x) * bytesPerPixel + 1] = (byte)y;           // green
                        image[(y * width + x) * bytesPerPixel + 2] = (byte)(255 - y);   // red
                    }
                }

                // write it to the frame
                IWICBitmapFrameEncodeExtensions.WritePixels(frame, height, width * bytesPerPixel, image);

                // commit everything to stream
                frame.Commit();
                pngEncoder.Commit();
            }
        }
コード例 #7
0
ファイル: WicBitmapDecoder.cs プロジェクト: smourier/WicNet
        public static WicBitmapDecoder Load(IStream stream, Guid?guidVendor = null, WICDecodeOptions options = WICDecodeOptions.WICDecodeMetadataCacheOnDemand)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            return(new WicBitmapDecoder(WICImagingFactory.CreateDecoderFromStream(stream, guidVendor, options)));
        }
コード例 #8
0
ファイル: WicBitmapDecoder.cs プロジェクト: smourier/WicNet
        public static WicBitmapDecoder Load(IntPtr fileHandle, Guid?guidVendor = null, WICDecodeOptions options = WICDecodeOptions.WICDecodeMetadataCacheOnDemand)
        {
            if (fileHandle == null)
            {
                throw new ArgumentNullException(nameof(fileHandle));
            }

            return(new WicBitmapDecoder(WICImagingFactory.CreateDecoderFromFileHandle(fileHandle, guidVendor, options)));
        }
コード例 #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("Re-encoding image lossless with metadata...");
            try
            {
                string filePath = args[0];

                var wic = new WICImagingFactory();

                using var fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);

                var decoder = wic.CreateDecoderFromStream(fileStream.AsCOMStream(), WICDecodeOptions.WICDecodeMetadataCacheOnDemand /*lossless decoding/encoding*/);

                var frame = decoder.GetFrame(0);

                using var memoryStream = new MemoryStream();

                var encoder = wic.CreateEncoder(decoder.GetContainerFormat());

                encoder.Initialize(memoryStream.AsCOMStream(), WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);

                var frameEncoder = encoder.CreateNewFrame();
                frameEncoder.Initialize(null);
                frameEncoder.SetSize(frame.GetSize());               // lossless decoding/encoding
                frameEncoder.SetResolution(frame.GetResolution());   // lossless decoding/encoding
                frameEncoder.SetPixelFormat(frame.GetPixelFormat()); // lossless decoding/encoding

                frameEncoder.AsMetadataBlockWriter().InitializeFromBlockReader(frame.AsMetadataBlockReader());

                var metadataWriter = frameEncoder.GetMetadataQueryWriter();

                metadataWriter.SetMetadataByName("System.Keywords", new string[] { "lossless", "re-encode", "with", "metadata" });

                frameEncoder.WriteSource(frame);

                frameEncoder.Commit();
                encoder.Commit();

                memoryStream.Flush();
                memoryStream.Position = 0;
                fileStream.Position   = 0;
                fileStream.SetLength(0);
                memoryStream.CopyTo(fileStream);

                Console.WriteLine("Image successfully lossless re-encoded with metadata!");
            }
            catch (Exception ex) when(ex.HResult == WinCodecError.PROPERTY_NOT_SUPPORTED)
            {
                Console.WriteLine("The file format does not support the requested metadata.");
            }
            catch (Exception ex) when(ex.HResult == WinCodecError.UNSUPPORTED_OPERATION)
            {
                Console.WriteLine("The file format does not support any metadata.");
            }
            Console.ReadKey();
        }
コード例 #10
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);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: smourier/WicNet
        static void CopyGif()
        {
            using (var dec = WicBitmapDecoder.Load(@"source.gif"))
            {
                var reader = dec.GetMetadataQueryReader();
                Dump(reader);
                Console.WriteLine();

                foreach (var frame in dec)
                {
                    Console.WriteLine(frame.Size);

                    reader = frame.GetMetadataReader();
                    Dump(reader);
                    Console.WriteLine();
                }


                using (var encoder = WICImagingFactory.CreateEncoder(dec.ContainerFormat))
                {
                    using (var file = File.OpenWrite("test.gif"))
                    {
                        var mis = new ManagedIStream(file);
                        encoder.Initialize(mis);

                        foreach (var frame in dec)
                        {
                            var newFrame = encoder.CreateNewFrame();
                            newFrame.Initialize();

                            var md = frame.GetMetadataReader().Enumerate();
                            using (var writer = newFrame.GetMetadataQueryWriter())
                            {
                                writer.EncodeMetadata(md);

                                // change delay here
                                writer.SetMetadataByName("/grctlext/Delay", (ushort)5);
                            }

                            if (frame.Palette != null)
                            {
                                newFrame.SetPalette(frame.Palette.ComObject);
                            }

                            newFrame.WriteSource(frame.ComObject);
                            newFrame.Item1.Commit();
                        }
                        encoder.Commit();
                    }
                }
            }
        }
コード例 #12
0
ファイル: WicBitmapDecoder.cs プロジェクト: smourier/WicNet
        public static WicBitmapDecoder Load(string filePath, Guid?guidVendor = null, FileAccess access = FileAccess.Read, WICDecodeOptions options = WICDecodeOptions.WICDecodeMetadataCacheOnDemand)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(null, filePath);
            }

            return(new WicBitmapDecoder(WICImagingFactory.CreateDecoderFromFilename(filePath, guidVendor, access, metadataOptions: options)));
        }
コード例 #13
0
        void CheckGetColorContexts(MainForm form, DataEntry[] de, Func <uint, IWICColorContext[], uint> method)
        {
            IWICColorContext[] contexts = null;
            IWICImagingFactory factory  = new WICImagingFactory() as IWICImagingFactory;

            try
            {
                try
                {
                    contexts = new IWICColorContext[method(0, null)];
                }
                catch (Exception e)
                {
                    form.CheckHRESULT(this, WinCodecError.WINCODEC_ERR_UNSUPPORTEDOPERATION, e, "0, NULL", de);

                    return;
                }
                if (contexts.Length > 0)
                {
                    for (int i = 0; i < contexts.Length; i++)
                    {
                        contexts[i] = factory.CreateColorContext();
                    }
                    try
                    {
                        method((uint)contexts.Length, contexts);

                        int index = 0;
                        foreach (IWICColorContext c in contexts)
                        {
                            if (c == null)
                            {
                                form.Add(this, method.ToString(Resources._0_NULLItem), de, new DataEntry(Resources.Index, index));
                            }
                            index++;
                        }
                    }
                    catch (Exception e)
                    {
                        form.Add(this, method.ToString(Resources._0_Failed), de, new DataEntry(e));
                    }
                }
            }
            finally
            {
                contexts.ReleaseComObject();
                factory.ReleaseComObject();
            }
        }
コード例 #14
0
 public static IWICPalette?GetColorPalette(this IWICBitmapSource bitmapSource)
 {
     try
     {
         var         wic          = new WICImagingFactory();
         IWICPalette colorPalette = wic.CreatePalette();
         bitmapSource.CopyPalette(colorPalette);
         return(colorPalette);
     }
     catch (Exception exception) when(exception.HResult == WinCodecError.PALETTE_UNAVAILABLE)
     {
         // no color palette available
         return(null);
     }
 }
コード例 #15
0
        public void Clip(int left, int top, int width, int height)
        {
            var rect = new WICRect();

            rect.X      = left;
            rect.Y      = top;
            rect.Width  = width;
            rect.Height = height;

            var clip = WICImagingFactory.CreateBitmapClipper();

            clip.Object.Initialize(_comObject.Object, ref rect).ThrowOnError();
            _comObject?.Dispose();
            _comObject = clip;
        }
コード例 #16
0
        static void Main(string[] args)
        {
            const int width         = 256;
            const int height        = 256;
            const int bytesPerPixel = 3;

            var wic = new WICImagingFactory();

            var encoder = wic.CreateEncoder(ContainerFormat.Jpeg);

            using (var stream = File.Create("result.jpeg"))
            {
                encoder.Initialize(stream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);

                var frame = encoder.CreateNewFrame(out IPropertyBag2 options);

                options.Write("ImageQuality", 0.1f); // set image quality encoder option

                frame.Initialize(options);

                frame.SetPixelFormat(WICPixelFormat.WICPixelFormat24bppBGR);
                frame.SetResolution(new Resolution(96, 96));
                frame.SetSize(width, height);

                var imageData = new byte[width * height * bytesPerPixel];

                // create a RGB gradient image
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        imageData[(y * width + x) * bytesPerPixel + 0] = (byte)x;           // blue
                        imageData[(y * width + x) * bytesPerPixel + 1] = (byte)y;           // green
                        imageData[(y * width + x) * bytesPerPixel + 2] = (byte)(255 - y);   // red
                    }
                }

                // write it to the frame
                IWICBitmapFrameEncodeExtensions.WritePixels(frame, height, width * bytesPerPixel, imageData);

                // commit everything to stream
                frame.Commit();
                encoder.Commit();
            }
        }
コード例 #17
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);
        }
コード例 #18
0
        public void CenterClip(int?width, int?height)
        {
            if (!width.HasValue && !height.HasValue)
            {
                return;
            }

            var rect = new WICRect();
            int w    = Width;
            int h    = Height;

            if (width.HasValue && width.Value < w)
            {
                rect.Width = width.Value;
                rect.X     = (w - width.Value) / 2;
            }
            else
            {
                rect.Width = w;
                rect.X     = 0;
            }

            if (height.HasValue && height.Value < h)
            {
                rect.Height = height.Value;
                rect.Y      = (h - height.Value) / 2;
            }
            else
            {
                rect.Height = h;
                rect.Y      = 0;
            }

            var clip = WICImagingFactory.CreateBitmapClipper();

            clip.Object.Initialize(_comObject.Object, ref rect).ThrowOnError();
            _comObject?.Dispose();
            _comObject = clip;
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: sbaeumlisberger/WIC-DotNet
        static void Main(string[] args)
        {
            Console.WriteLine("Encoding metadata in-place...");
            try
            {
                string filePath = args[0];

                var wic = new WICImagingFactory();

                using var fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);

                var decoder = wic.CreateDecoderFromStream(fileStream.AsCOMStream(), WICDecodeOptions.WICDecodeMetadataCacheOnDemand);

                var frame = decoder.GetFrame(0);

                var mtadataEncoder = wic.CreateFastMetadataEncoderFromFrameDecode(frame);

                var metadataWriter = mtadataEncoder.GetMetadataQueryWriter();

                metadataWriter.SetMetadataByName("System.Keywords", new string[] { "in-place", "metadata", "encoding" });

                mtadataEncoder.Commit();

                Console.WriteLine("Metadata successfully encoded!");
            }
            catch (Exception ex) when(ex.HResult == WinCodecError.PROPERTY_NOT_SUPPORTED)
            {
                Console.WriteLine("The file format does not support the requested metadata.");
            }
            catch (Exception ex) when(ex.HResult == WinCodecError.TOO_MUCH_METADATA ||
                                      ex.HResult == WinCodecError.INSUFFICIENT_BUFFER ||
                                      ex.HResult == WinCodecError.IMAGE_METADATA_HEADER_UNKNOWN ||
                                      ex.HResult == WinCodecError.UNSUPPORTED_OPERATION)
            {
                Console.WriteLine("The file has not enough padding for the requested metadata.");
            }
            Console.ReadKey();
        }
コード例 #20
0
        static void Main(string [] args)
        {
            IWICImagingFactory factory = new WICImagingFactory();

            factory.CreateDecoder(ContainerFormats.Png, Vendors.Microsoft, out IWICBitmapDecoder decoder);
            using (Stream inputStream = new FileStream("Test.png", FileMode.Open))
            {
                decoder.Initialize(inputStream.AsIStream(), WICDecodeOptions.MetadataCacheOnDemand);
                decoder.GetFrame(0, out IWICBitmapFrameDecode bitmapFrame);

                bitmapFrame.GetSize(out uint width, out uint height);
                bitmapFrame.GetResolution(out double dpiX, out double dpiY);
                Console.WriteLine($"Width: {width}, Height: {height}, DPI: {dpiX}x{dpiY}");

                factory.CreateFormatConverter(out IWICFormatConverter formatConverter);
                formatConverter.Initialize(bitmapFrame, PixelFormats.PixelFormat32bppBGRA, WICBitmapDitherType.None, null, 1, WICBitmapPaletteType.Custom);

                using (Stream outputStream = new FileStream("Output.png", FileMode.Create))
                {
                    factory.CreateEncoder(ContainerFormats.Png, Vendors.Microsoft, out IWICBitmapEncoder encoder);

                    encoder.Initialize(outputStream.AsIStream(), WICBitmapEncoderCacheOption.NoCache);
                    encoder.CreateNewFrame(out IWICBitmapFrameEncode frameEncode, out IPropertyBag2 encoderOptions);

                    frameEncode.Initialize(encoderOptions);
                    frameEncode.SetPixelFormat(PixelFormats.PixelFormat32bppBGRA);
                    frameEncode.SetSize(width, height);
                    frameEncode.SetResolution(dpiX, dpiY);

                    WICRect rect = new WICRect(0, 0, ( int )width, ( int )height);
                    frameEncode.WriteSource(formatConverter, ref rect);

                    frameEncode.Commit();

                    encoder.Commit();
                }
            }
        }
コード例 #21
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);
            }
        }
コード例 #22
0
ファイル: BitmapDecoderRule.cs プロジェクト: eakova/resizer
        void CheckGetColorContexts(MainForm form, DataEntry[] de, Func<uint, IWICColorContext[], uint> method)
        {
            IWICColorContext[] contexts = null;
            IWICImagingFactory factory = new WICImagingFactory() as IWICImagingFactory;
            try
            {
                try
                {
                    contexts = new IWICColorContext[method(0, null)];
                }
                catch (Exception e)
                {
                    form.CheckHRESULT(this, WinCodecError.WINCODEC_ERR_UNSUPPORTEDOPERATION, e, "0, NULL", de);

                    return;
                }
                if (contexts.Length > 0)
                {
                    for (int i = 0; i < contexts.Length; i++)
                    {
                        contexts[i] = factory.CreateColorContext();
                    }
                    try
                    {
                        method((uint)contexts.Length, contexts);

                        int index = 0;
                        foreach (IWICColorContext c in contexts)
                        {
                            if (c == null)
                            {
                                form.Add(this, method.ToString(Resources._0_NULLItem), de, new DataEntry(Resources.Index, index));
                            }
                            index++;
                        }
                    }
                    catch (Exception e)
                    {
                        form.Add(this, method.ToString(Resources._0_Failed), de, new DataEntry(e));
                    }
                }
            }
            finally
            {
                contexts.ReleaseComObject();
                factory.ReleaseComObject();
            }
        }
コード例 #23
0
        public WicBitmapSource Clone(WICBitmapCreateCacheOption options = WICBitmapCreateCacheOption.WICBitmapNoCache)
        {
            var bmp = WICImagingFactory.CreateBitmapFromSource(_comObject, options);

            return(new WicBitmapSource(bmp));
        }
コード例 #24
0
        public void Save(
            Stream stream,
            Guid encoderContainerFormat,
            Guid?pixelFormat = null,
            WICBitmapEncoderCacheOption cacheOptions = WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache,
            IEnumerable <KeyValuePair <string, object> > encoderOptions = null,
            IEnumerable <WicMetadataKeyValue> metadata = null,
            WicPalette encoderPalette = null,
            WicPalette framePalette   = null,
            WICRect?sourceRectangle   = null)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (var encoder = WICImagingFactory.CreateEncoder(encoderContainerFormat))
            {
                var mis = new ManagedIStream(stream);
                encoder.Initialize(mis, cacheOptions);

                if (encoderPalette != null)
                {
                    // gifs...
                    encoder.SetPalette(encoderPalette.ComObject);
                }

                var frameBag = encoder.CreateNewFrame();

                if (encoderOptions != null)
                {
                    frameBag.Item2.Write(encoderOptions);
                }

                frameBag.Initialize();

                if (metadata?.Any() == true)
                {
                    using (var writer = frameBag.GetMetadataQueryWriter())
                    {
                        writer.EncodeMetadata(metadata);
                    }
                }

                if (pixelFormat.HasValue)
                {
                    frameBag.SetPixelFormat(pixelFormat.Value);
                }

                if (framePalette != null)
                {
                    frameBag.Item1.SetPalette(framePalette.ComObject);
                }

                // "WIC error 0x88982F0C. The component is not initialized" here can mean the palette is not set
                // "WIC error 0x88982F45. The bitmap palette is unavailable" here means for example we're saving a file that doesn't support palette (even if we called SetPalette before, it may be useless)
                frameBag.WriteSource(_comObject, sourceRectangle);
                frameBag.Item1.Commit();
                encoder.Commit();
            }
        }
コード例 #25
0
 public static WicBitmapSource FromSourceRect(WicBitmapSource source, int x, int y, int width, int height) => new WicBitmapSource(WICImagingFactory.CreateBitmapFromSourceRect(source?.ComObject, x, y, width, height));
コード例 #26
0
        public void Scale(int?width, int?height, WICBitmapInterpolationMode mode = WICBitmapInterpolationMode.WICBitmapInterpolationModeNearestNeighbor, WicBitmapScaleOptions options = WicBitmapScaleOptions.Default)
        {
            if (!width.HasValue && !height.HasValue)
            {
                return;
            }

            if (width.HasValue && width.Value <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(width));
            }

            if (height.HasValue && height.Value <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(height));
            }

            int neww;
            int newh;

            if (width.HasValue && height.HasValue)
            {
                neww = width.Value;
                newh = height.Value;
            }
            else
            {
                int w = Width;
                int h = Height;
                if (w == 0 || h == 0)
                {
                    return;
                }

                if (width.HasValue)
                {
                    if ((options & WicBitmapScaleOptions.DownOnly) == WicBitmapScaleOptions.DownOnly)
                    {
                        if (width.Value > w)
                        {
                            return;
                        }
                    }

                    neww = width.Value;
                    newh = width.Value * h / w;
                }
                else // height.HasValue
                {
                    if ((options & WicBitmapScaleOptions.DownOnly) == WicBitmapScaleOptions.DownOnly)
                    {
                        if (height.Value > h)
                        {
                            return;
                        }
                    }

                    newh = height.Value;
                    neww = height.Value * w / h;
                }
            }

            if (neww == 0 || newh == 0)
            {
                return;
            }

            var clip = WICImagingFactory.CreateBitmapScaler();

            clip.Object.Initialize(_comObject.Object, neww, newh, mode).ThrowOnError();
            _comObject?.Dispose();
            _comObject = clip;
        }
コード例 #27
0
 public static WicBitmapSource FromSource(WicBitmapSource source, WICBitmapCreateCacheOption option = WICBitmapCreateCacheOption.WICBitmapNoCache) => new WicBitmapSource(WICImagingFactory.CreateBitmapFromSource(source?.ComObject, option));
コード例 #28
0
 public static WicBitmapSource FromHBitmap(IntPtr bitmapHandle, IntPtr paletteHandle, WICBitmapAlphaChannelOption options = WICBitmapAlphaChannelOption.WICBitmapUseAlpha) => new WicBitmapSource(WICImagingFactory.CreateBitmapFromHBITMAP(bitmapHandle, paletteHandle, options));
コード例 #29
0
 public static WicBitmapSource FromMemory(int width, int height, Guid pixelFormat, int stride, byte[] buffer) => new WicBitmapSource(WICImagingFactory.CreateBitmapFromMemory(width, height, pixelFormat, stride, buffer));
コード例 #30
0
 public static WicBitmapSource FromHIcon(IntPtr iconHandle) => new WicBitmapSource(WICImagingFactory.CreateBitmapFromHICON(iconHandle));
コード例 #31
0
 public WicBitmapSource(int width, int height, Guid pixelFormat, WICBitmapCreateCacheOption option = WICBitmapCreateCacheOption.WICBitmapCacheOnDemand)
 {
     _comObject = WICImagingFactory.CreateBitmap(width, height, pixelFormat, option);
 }