Esempio n. 1
1
        private static Texture DecodeMultiframe(ImagingFactory imagingFactory, WicFlags flags, TextureDescription description, BitmapDecoder decoder)
        {
            var texture = new Texture(description);
              Guid dstFormat = ToWic(description.Format, false);

              for (int index = 0; index < description.ArraySize; ++index)
              {
            var image = texture.Images[index];
            using (var frame = decoder.GetFrame(index))
            {
              var pfGuid = frame.PixelFormat;
              var size = frame.Size;

              if (size.Width == description.Width && size.Height == description.Height)
              {
            // This frame does not need resized
            if (pfGuid == dstFormat)
            {
              frame.CopyPixels(image.Data, image.RowPitch);
            }
            else
            {
              using (var converter = new FormatConverter(imagingFactory))
              {
                converter.Initialize(frame, dstFormat, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
                converter.CopyPixels(image.Data, image.RowPitch);
              }
            }
              }
              else
              {
            // This frame needs resizing
            using (var scaler = new BitmapScaler(imagingFactory))
            {
              scaler.Initialize(frame, description.Width, description.Height, GetWicInterp(flags));

              Guid pfScaler = scaler.PixelFormat;
              if (pfScaler == dstFormat)
              {
                scaler.CopyPixels(image.Data, image.RowPitch);
              }
              else
              {
                // The WIC bitmap scaler is free to return a different pixel format than the source image, so here we
                // convert it to our desired format
                using (var converter = new FormatConverter(imagingFactory))
                {
                  converter.Initialize(scaler, dstFormat, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
                  converter.CopyPixels(image.Data, image.RowPitch);
                }
              }
            }
              }
            }
              }

              return texture;
        }
        public static void LoadSource(Stream str, UIImage img)
        {
            Wic.ImagingFactory fac = ThreadResource.GetWicFactory();
            var d = new Wic.BitmapDecoder(fac, str, Wic.DecodeOptions.CacheOnLoad);

            if (img.data != null)
            {
                ClearResource(img);
            }
            img.data    = str;
            img.Decoder = d;
            var frame = d.GetFrame(0);

            img.FrameDecoder = frame;
            var fconv = new Wic.FormatConverter(fac);

            fconv.Initialize(frame, Wic.PixelFormat.Format32bppPRGBA);
            img.Bitmap         = fconv;
            img.Mapsize.Left   = 0;
            img.Mapsize.Top    = 0;
            img.Mapsize.Right  = img.Bitmap.Size.Width;
            img.Mapsize.Bottom = img.Bitmap.Size.Height;
            lock (DX_Core.D2D)
                img.d2dmap = D2D1.Bitmap.FromWicBitmap(DX_Core.D2D.d2dContext, img.Bitmap);
        }
Esempio n. 3
0
            void ColorCameraLoop()
            {
                while (true)
                {
                    var encodedColorData = camera.Client.LatestJPEGImage();

                    // decode JPEG
                    var memoryStream = new MemoryStream(encodedColorData);
                    var stream       = new WICStream(imagingFactory, memoryStream);
                    // decodes to 24 bit BGR
                    var decoder           = new SharpDX.WIC.BitmapDecoder(imagingFactory, stream, SharpDX.WIC.DecodeOptions.CacheOnLoad);
                    var bitmapFrameDecode = decoder.GetFrame(0);

                    // convert to 32 bpp
                    var formatConverter = new FormatConverter(imagingFactory);
                    formatConverter.Initialize(bitmapFrameDecode, SharpDX.WIC.PixelFormat.Format32bppBGR);
                    formatConverter.CopyPixels(nextColorData, Kinect2Calibration.colorImageWidth * 4); // TODO: consider copying directly to texture native memory
                    //lock (colorData)
                    //    Swap<byte[]>(ref colorData, ref nextColorData);
                    lock (renderLock) // necessary?
                    {
                        UpdateColorImage(device.ImmediateContext, nextColorData);
                    }
                    memoryStream.Close();
                    memoryStream.Dispose();
                    stream.Dispose();
                    decoder.Dispose();
                    formatConverter.Dispose();
                    bitmapFrameDecode.Dispose();
                }
            }
Esempio n. 4
0
 public D2D1.Bitmap LoadImage(Stream stream)
 {
     using (var converter = new WIC.FormatConverter(_renderBase.WicFactory))
         using (var scaler = new WIC.BitmapScaler(_renderBase.WicFactory))
             using (var rotater = new WIC.BitmapFlipRotator(_renderBase.WicFactory))
                 using (var bmd = new WIC.BitmapDecoder(_renderBase.WicFactory, stream, WIC.DecodeOptions.CacheOnDemand))
                     using (var frame = bmd.GetFrame(0))
                     {
                         /*
                          *              var rotation = GetExifRotation(frame);
                          *              var size = frame.Size;
                          *              scaler.Initialize(frame, (int) (size.Width + 0.5), (int) (size.Height + 0.5), WIC.BitmapInterpolationMode.HighQualityCubic);
                          *              converter.Initialize(scaler, WIC.PixelFormat.Format32bppPRGBA);
                          * return (
                          *  D2D1.Bitmap.FromWicBitmap(Target, converter),
                          *  GetMatrix(frame, rotation),
                          *  GetSize(frame, rotation)
                          * );
                          */
                         var size = frame.Size;
                         scaler.Initialize(frame, (int)size.Width, (int)size.Height, WIC.BitmapInterpolationMode.Linear);
                         converter.Initialize(scaler, WIC.PixelFormat.Format32bppPBGRA);
                         rotater.Initialize(converter, GetExifRotation(frame));
                         return(D2D1.Bitmap.FromWicBitmap(Target, rotater));
                     }
 }
Esempio n. 5
0
        private D3D11.ShaderResourceView LoadTexture(string name)
        {
            var converter = new SharpDX.WIC.FormatConverter(imagingFactory);
            var decoder   = new SharpDX.WIC.BitmapDecoder(imagingFactory, name, SharpDX.WIC.DecodeOptions.CacheOnDemand);

            converter.Initialize(decoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppBGRA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom);

            var stride     = converter.Size.Width * 4;
            var size       = converter.Size.Height * stride;
            var dataStream = new SharpDX.DataStream(size, true, true);

            converter.CopyPixels(stride, dataStream);
            D3D11.Texture2D tex = new D3D11.Texture2D(d3dDevice,
                                                      new D3D11.Texture2DDescription()
            {
                Width             = converter.Size.Width,
                Height            = converter.Size.Height,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Immutable,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            },
                                                      new SharpDX.DataRectangle(dataStream.DataPointer, stride)
                                                      );

            return(new D3D11.ShaderResourceView(d3dDevice, tex));
        }
Esempio n. 6
0
        public static D2D.Bitmap LoadBitmap(D2D.RenderTarget renderTarget, string imagePath)
        {
            FileInfo fi = new FileInfo(imagePath);

            if (!fi.Exists)
            {
                var    ext    = fi.Extension;
                string newExt = "";
                if (ext == ".jpg")
                {
                    newExt = ".png";
                }
                else if (ext == ".png")
                {
                    newExt = ".jpg";
                }
                string newName = fi.FullName.Remove(fi.FullName.Length - 4, 4);
                imagePath = newName + newExt;
            }

            D2D.Bitmap bmp;
            if (Cached.ContainsKey(imagePath))
            {
                bmp = Cached[imagePath];
                if (bmp.IsDisposed)
                {
                    Cached.TryRemove(imagePath, out _);
                }
                else
                {
                    return(bmp);
                }
            }

            WIC.ImagingFactory    imagingFactory = new WIC.ImagingFactory();
            DXIO.NativeFileStream fileStream     = new DXIO.NativeFileStream(imagePath,
                                                                             DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read);

            WIC.BitmapDecoder bitmapDecoder =
                new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand);
            WIC.BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

            WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory);
            converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA);

            var bitmapProperties =
                new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));

            //Size2 size = new Size2(frame.Size.Width, frame.Size.Height);

            bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties);

            if (!Cached.ContainsKey(imagePath))
            {
                Cached.TryAdd(imagePath, bmp);
                //LogUtil.LogInfo("Created cache.");
            }

            return(bmp);
        }
        private static Direct2D.Bitmap LoadFromFile(string filename, Direct2D.RenderTarget Direct2DTarget)
        {
            var factory = new WIC.ImagingFactory();
            // Decode image
            var decoder     = new WIC.BitmapDecoder(factory, filename, WIC.DecodeOptions.CacheOnLoad);
            var frameDecode = decoder.GetFrame(0);
            var source      = new WIC.BitmapSource(frameDecode.NativePointer);
            var fc          = new WIC.FormatConverter(factory);

            fc.Initialize(
                source,
                SharpDX.WIC.PixelFormat.Format32bppPBGRA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0f,
                SharpDX.WIC.BitmapPaletteType.Custom
                );
            double dpX = 96.0f;
            double dpY = 96.0f;

            fc.GetResolution(out dpX, out dpY);
            Direct2D.BitmapProperties props = new Direct2D.BitmapProperties(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            WIC.Bitmap bmp = new WIC.Bitmap(factory, fc, WIC.BitmapCreateCacheOption.CacheOnLoad);
            // Формируем изображения
            var Direct2DBitmap = SharpDX.Direct2D1.Bitmap.FromWicBitmap(Direct2DTarget, fc, props);

            // Cleanup
            factory.Dispose();
            decoder.Dispose();
            source.Dispose();
            fc.Dispose();
            return(Direct2DBitmap);
        }
Esempio n. 8
0
        private static BitmapSource LoadBitmap(Stream stream, out SharpDX.WIC.BitmapDecoder decoder)
        {
            if (imgfactory == null)
            {
                imgfactory = new ImagingFactory();
            }

            decoder = new SharpDX.WIC.BitmapDecoder(
                imgfactory,
                stream,
                DecodeOptions.CacheOnDemand
                );

            var fconv = new FormatConverter(imgfactory);

            using (var frame = decoder.GetFrame(0))
            {
                fconv.Initialize(
                    frame,
                    PixelFormat.Format32bppRGBA,
                    BitmapDitherType.None,
                    null,
                    0.0,
                    BitmapPaletteType.Custom);
            }
            return(fconv);
        }
Esempio n. 9
0
 public void Create(string filename)
 {
     using (var decoder = new s.WIC.BitmapDecoder(
                SDFactory.WicImagingFactory,
                filename,
                s.WIC.DecodeOptions.CacheOnDemand))
         Initialize(decoder);
 }
Esempio n. 10
0
 public void Create(System.IO.Stream stream)
 {
     using (var decoder = new s.WIC.BitmapDecoder(
                SDFactory.WicImagingFactory,
                stream,
                s.WIC.DecodeOptions.CacheOnDemand))
         Initialize(decoder);
 }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BitmapImpl"/> class.
        /// </summary>
        /// <param name="factory">The WIC imaging factory to use.</param>
        /// <param name="stream">The stream to read the bitmap from.</param>
        public BitmapImpl(ImagingFactory factory, Stream stream)
        {
            _factory = factory;

            using (BitmapDecoder decoder = new BitmapDecoder(factory, stream, DecodeOptions.CacheOnLoad))
            {
                WicImpl = new Bitmap(factory, decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnLoad);
            }
        }
Esempio n. 12
0
        public BitmapImpl(ImagingFactory factory, string fileName)
        {
            this.factory = factory;

            using (BitmapDecoder decoder = new BitmapDecoder(factory, fileName, DecodeOptions.CacheOnDemand))
            {
                this.WicImpl = new Bitmap(factory, decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnDemand);
            }
        }
Esempio n. 13
0
        public void Load(string filename, System.Threading.CancellationToken token)
        {
            int stride;
            var imgF = new ImagingFactory();

            using (var decoder = new SharpDX.WIC.BitmapDecoder(imgF, filename, SharpDX.IO.NativeFileAccess.Read, DecodeOptions.CacheOnLoad))
                using (var frame = decoder.GetFrame(0))
                {
                    var  format      = PixelToTextureFormat(frame.PixelFormat);
                    bool knownFormat = format != Format.Unknown;

                    var w = frame.Size.Width;
                    var h = frame.Size.Height;
                    stride = PixelFormat.GetStride(knownFormat ? frame.PixelFormat:PixelFormat.Format32bppRGBA, w);
                    //stride = PixelFormat.GetStride(PixelFormat.Format32bppBGRA, w);
                    FLength = stride * h;

                    Description = new Texture2DDescription()
                    {
                        ArraySize         = 1,
                        BindFlags         = BindFlags.ShaderResource,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Format            = knownFormat?format:Format.R8G8B8A8_UNorm,
                        MipLevels         = 1,
                        OptionFlags       = ResourceOptionFlags.None,
                        Usage             = ResourceUsage.Default,
                        Width             = w,
                        Height            = h,
                        SampleDescription = new SampleDescription(1, 0)
                    };
                    token.ThrowIfCancellationRequested();
                    ptr = mp.UnmanagedPool.GetMemory(FLength);
                    //if (frame.PixelFormat != PixelFormat.Format32bppBGRA)
                    if (!knownFormat)
                    {
                        using (var converter = new FormatConverter(imgF))
                        {
                            converter.Initialize(frame, PixelFormat.Format32bppRGBA);
                            converter.CopyPixels(stride, ptr, FLength);
                        }
                    }
                    else
                    {
                        frame.CopyPixels(stride, ptr, FLength);
                    }
                }
            token.ThrowIfCancellationRequested();
            ds = new SlimDX.DataStream(ptr, FLength, true, false);
            var dr = new SlimDX.DataRectangle(stride, ds);

            token.ThrowIfCancellationRequested();
            tex = new Texture2D(Device, Description, dr);
            token.ThrowIfCancellationRequested();
            SRV = new ShaderResourceView(Device, tex);
        }
Esempio n. 14
0
        private static void LoadBitmaps()
        {
            var fac = new SharpDX.WIC.ImagingFactory();
            var target = GraphicsWindow.Instance.RenderTarget2D;
            var stream = new NativeFileStream(Application.StartupPath + "\\Images\\Ship 1.png", NativeFileMode.Open, NativeFileAccess.Read);
            var decoder = new BitmapDecoder(fac, stream, DecodeOptions.CacheOnDemand);
            var frame = decoder.GetFrame(0);
            var converter = new FormatConverter(fac);
            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            BitShip1 = Bitmap1.FromWicBitmap(GraphicsWindow.Instance.RenderTarget2D, converter);
        }
Esempio n. 15
0
 public D2D1.Bitmap LoadImage(Stream stream)
 {
     using (var converter = new WIC.FormatConverter(_renderBase.WicFactory))
         using (var scaler = new WIC.BitmapScaler(_renderBase.WicFactory))
             using (var bmd = new WIC.BitmapDecoder(_renderBase.WicFactory, stream, WIC.DecodeOptions.CacheOnLoad))
                 using (var frame = bmd.GetFrame(0))
                 {
                     var size = frame.Size;
                     scaler.Initialize(frame, (int)(size.Width + 0.5), (int)(size.Height + 0.5), WIC.BitmapInterpolationMode.HighQualityCubic);
                     converter.Initialize(scaler, WIC.PixelFormat.Format32bppPRGBA);
                     return(D2D1.Bitmap.FromWicBitmap(Target, converter));
                 }
 }
Esempio n. 16
0
        public static byte[] LoadImage(string fileName, bool premultiplied, out int width, out int height)
        {
            WIC.ImagingFactory factory = new WIC.ImagingFactory();

            SharpDX.IO.NativeFileStream stream  = new SharpDX.IO.NativeFileStream(fileName, SharpDX.IO.NativeFileMode.Open, SharpDX.IO.NativeFileAccess.Read);
            WIC.BitmapDecoder           decoder = new WIC.BitmapDecoder(factory, stream, WIC.DecodeOptions.CacheOnDemand);
            WIC.BitmapFrameDecode       frame   = decoder.GetFrame(0);
            width  = frame.Size.Width;
            height = frame.Size.Height;
            byte[] data = new byte[width * height * 4];
            frame.CopyPixels(data, width * 4);
            return(data);
        }
Esempio n. 17
0
        public static D2D.Bitmap LoadBitmap(this D2D.RenderTarget renderTarget, string imagePath)
        {
            lock (LockObj)
            {
                Sw.Start();
                D2D.Bitmap bmp;
                if (Cached.ContainsKey(imagePath))
                {
                    Cached[imagePath].Time = DateTime.Now;
                    bmp = Cached[imagePath].Bitmap;

                    Sw.Stop();
                    LogUtil.LogInfo($"Cache: {Sw.ElapsedMilliseconds}ms.");
                }
                else
                {
                    WIC.ImagingFactory    imagingFactory = new WIC.ImagingFactory();
                    DXIO.NativeFileStream fileStream     = new DXIO.NativeFileStream(imagePath,
                                                                                     DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read);

                    WIC.BitmapDecoder     bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand);
                    WIC.BitmapFrameDecode frame         = bitmapDecoder.GetFrame(0);

                    WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory);
                    converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA);

                    var bitmapProperties =
                        new D2D.BitmapProperties(new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied));
                    //Size2 size = new Size2(frame.Size.Width, frame.Size.Height);

                    bmp = D2D.Bitmap.FromWicBitmap(renderTarget, converter, bitmapProperties);

                    Sw.Stop();
                    LogUtil.LogInfo($"Load: {Sw.ElapsedMilliseconds}ms.");
                }

                if (!Cached.ContainsKey(imagePath) && Sw.ElapsedMilliseconds > 50)
                {
                    Cached.TryAdd(imagePath, new CacheInfo(DateTime.Now, bmp));
                    LogUtil.LogInfo("Created cache.");
                    if (Cached.Count > 50)
                    {
                        Cached.TryRemove(Cached.OrderByDescending(c => c.Value.Time).First().Key, out _);
                        LogUtil.LogInfo("Removed unused cache.");
                    }
                }
                Sw.Reset();

                return(bmp);
            }
        }
Esempio n. 18
0
 public BblBitmapSource(string filePath)
 {
     if (filePath == null)
     {
         throw new ArgumentNullException(nameof(filePath));
     }
     using (var fac = new ImagingFactory())
     {
         using (var dec = new SharpDX.WIC.BitmapDecoder(fac, filePath, DecodeOptions.CacheOnDemand))
         {
             WICBitmapSource = dec.GetFrame(0);
         }
     }
 }
Esempio n. 19
0
        private static Direct2D1.Bitmap1 CreateD2dBitmap(
            WIC.ImagingFactory imagingFactory,
            string filename,
            Direct2D1.DeviceContext renderTarget)
        {
            var decoder = new WIC.BitmapDecoder(imagingFactory, filename, WIC.DecodeOptions.CacheOnLoad);

            WIC.BitmapFrameDecode frame = decoder.GetFrame(0);

            var image = new WIC.FormatConverter(imagingFactory);

            image.Initialize(frame, WIC.PixelFormat.Format32bppPBGRA);
            return(Direct2D1.Bitmap1.FromWicBitmap(renderTarget, image));
        }
Esempio n. 20
0
        public static D2D.Bitmap LoadFromFile(D2D.RenderTarget renderTarget, string filePath)
        {
            WIC.ImagingFactory    imagingFactory = new WIC.ImagingFactory();
            DXIO.NativeFileStream fileStream     = new DXIO.NativeFileStream(filePath,
                                                                             DXIO.NativeFileMode.Open, DXIO.NativeFileAccess.Read);

            WIC.BitmapDecoder     bitmapDecoder = new WIC.BitmapDecoder(imagingFactory, fileStream, WIC.DecodeOptions.CacheOnDemand);
            WIC.BitmapFrameDecode frame         = bitmapDecoder.GetFrame(0);

            WIC.FormatConverter converter = new WIC.FormatConverter(imagingFactory);
            converter.Initialize(frame, WIC.PixelFormat.Format32bppPRGBA);

            return(D2D.Bitmap.FromWicBitmap(RenderForm.RenderTarget, converter));
        }
        private static d2.Bitmap Load(d2.DeviceContext device, wic.BitmapDecoder decoder)
        {
            var converter = new wic.FormatConverter(Factory);
            var frame     = decoder.GetFrame(0);

            converter.Initialize(frame, wic.PixelFormat.Format32bppPRGBA);
            var bmp = d2.Bitmap.FromWicBitmap(device, converter);

            frame.Dispose();
            decoder.Dispose();
            converter.Dispose();

            return(bmp);
        }
Esempio n. 22
0
 private static WIC.FormatConverter CreateWicImage(WIC.ImagingFactory2 wic, Stream imageStream, Guid imageFormatGuid)
 {
     using (var decoder = new WIC.BitmapDecoder(wic, imageFormatGuid))
     {
         var decodeStream = new WIC.WICStream(wic, imageStream);
         decoder.Initialize(decodeStream, WIC.DecodeOptions.CacheOnLoad);
         using (var decodeFrame = decoder.GetFrame(0))
         {
             var converter = new WIC.FormatConverter(wic);
             converter.Initialize(decodeFrame, WIC.PixelFormat.Format32bppPBGRA);
             return(converter);
         }
     }
 }
Esempio n. 23
0
        public static Texture2D LoadTextureFromFile(SharpDX.Direct3D11.Device aDevice, string aFullPath)
        {
            Texture2D      result = null;
            ImagingFactory fac    = new ImagingFactory();

            BitmapDecoder     bc  = new SharpDX.WIC.BitmapDecoder(fac, aFullPath, DecodeOptions.CacheOnLoad);
            BitmapFrameDecode bfc = bc.GetFrame(0);
            FormatConverter   fc  = new FormatConverter(fac);

            System.Guid desiredFormat = PixelFormat.Format32bppBGRA;
            fc.Initialize(bfc, desiredFormat);

            float[] buffer = new float[fc.Size.Width * fc.Size.Height];

            bool canConvert = fc.CanConvert(bfc.PixelFormat, desiredFormat);

            fc.CopyPixels <float>(buffer);
            GCHandle handle      = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            float    sizeOfPixel = PixelFormat.GetBitsPerPixel(desiredFormat) / 8;

            if (sizeOfPixel != 4.0f)
            {
                throw new System.Exception("Unknown error");
            }

            DataBox db = new DataBox(handle.AddrOfPinnedObject(), fc.Size.Width * (int)sizeOfPixel, fc.Size.Width * fc.Size.Height * (int)sizeOfPixel);

            int width  = fc.Size.Width;
            int height = fc.Size.Height;

            Texture2DDescription fTextureDesc = new Texture2DDescription();

            fTextureDesc.CpuAccessFlags    = CpuAccessFlags.None;
            fTextureDesc.Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            fTextureDesc.Width             = width;
            fTextureDesc.Height            = height;
            fTextureDesc.Usage             = ResourceUsage.Default;
            fTextureDesc.MipLevels         = 1;
            fTextureDesc.ArraySize         = 1;
            fTextureDesc.OptionFlags       = ResourceOptionFlags.None;
            fTextureDesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            fTextureDesc.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);

            result = new Texture2D(aDevice, fTextureDesc, new DataBox[] { db });
            handle.Free();

            return(result);
        }
Esempio n. 24
0
        public IImage LoadImage(Stream stream)
        {
            var factories = Direct2DFactories.Shared;
            var d = new WIC.BitmapDecoder (factories.WICFactory, stream, WIC.DecodeOptions.CacheOnDemand);
            WIC.BitmapSource b = d.GetFrame (0);

            var renderFormat = WIC.PixelFormat.Format32bppPBGRA;
            if (b.PixelFormat != renderFormat) {
                //System.Diagnostics.Debug.WriteLine ("BMP FORMAT: " + b.PixelFormat);
                var c = new WIC.FormatConverter (factories.WICFactory);
                c.Initialize (b, renderFormat);
                //System.Diagnostics.Debug.WriteLine ("CO  FORMAT: " + c.PixelFormat);
                b = c;
            }

            // Convert the BitmapSource to a Bitmap so we can allow the decoder to go out of memory
            return new WICBitmapSourceImage (new WIC.Bitmap (factories.WICFactory, b, WIC.BitmapCreateCacheOption.CacheOnLoad), factories);
        }
Esempio n. 25
0
        public static WIC.BitmapSource LoadBitmap(WIC.ImagingFactory2 factory, string filename)
        {
            var bitmapDecoder = new WIC.BitmapDecoder(
                factory,
                filename,
                WIC.DecodeOptions.CacheOnDemand);

            var formatConverter = new WIC.FormatConverter(factory);

            formatConverter.Initialize(
                bitmapDecoder.GetFrame(0),
                WIC.PixelFormat.Format32bppPRGBA,
                WIC.BitmapDitherType.None,
                null,
                0.0,
                WIC.BitmapPaletteType.Custom);

            return(formatConverter);
        }
Esempio n. 26
0
        public static WICBitmap LoadBitmap(string rele_path)
        {
            var Imgc     = new ImagingFactory();
            var Demcoder = new BitmapDecoder(Imgc, rele_path, SharpDX.IO.NativeFileAccess.Read, DecodeOptions.CacheOnLoad);

            BitmapFrameDecode nm_opb = Demcoder.GetFrame(0);
            var convert = new FormatConverter(Imgc);

            convert.Initialize(nm_opb, SharpDX.WIC.PixelFormat.Format32bppPBGRA);

            var Init_action = new WICBitmap(Imgc, convert, BitmapCreateCacheOption.CacheOnLoad);

            Imgc.Dispose();
            Demcoder.Dispose();
            nm_opb.Dispose();
            convert.Dispose();

            return(Init_action);
        }
        public static BitmapSource LoadBitmap(ImagingFactory2 factory, string filename)
        {
            var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                factory,
                filename,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            var result = new SharpDX.WIC.FormatConverter(factory);

            result.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0,
                SharpDX.WIC.BitmapPaletteType.Custom);

            return result;
        }
Esempio n. 28
0
        Bitmap1 createD2DBitmap(string filePath, _d2d.DeviceContext deviceContext)
        {
            var imagingFactory = new _wic.ImagingFactory();

            var fileStream = new NativeFileStream(
                filePath,
                NativeFileMode.Open,
                NativeFileAccess.Read);

            var bitmapDecoder = new _wic.BitmapDecoder(imagingFactory, fileStream, _wic.DecodeOptions.CacheOnDemand);
            var frame         = bitmapDecoder.GetFrame(0);

            var converter = new _wic.FormatConverter(imagingFactory);

            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            var newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(deviceContext, converter);

            return(newBitmap);
        }
Esempio n. 29
0
 public BblBitmapSource(MemoryStream stream)
 {
     try
     {
         using (var fac = new ImagingFactory())
         {
             _pinnedArray = GCHandle.Alloc(stream.GetBuffer(), GCHandleType.Pinned);
             IntPtr pointer        = _pinnedArray.AddrOfPinnedObject();
             SharpDX.DataPointer p = new SharpDX.DataPointer(pointer, (int)stream.Length);
             using (WICStream wstream = new WICStream(fac, p))
             {
                 using (SharpDX.WIC.BitmapDecoder dec = new SharpDX.WIC.BitmapDecoder(fac, wstream, Guid.Empty, DecodeOptions.CacheOnDemand))
                 {
                     WICBitmapSource = dec.GetFrame(0);
                 }
             }
         }
     }
     catch (Exception e) { Console.WriteLine(e.Message); }
 }
        public BitmapSource LoadBitmap(ImagingFactory factory, string filename)
        {
            var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                factory,
                filename,
                SharpDX.WIC.DecodeOptions.CacheOnDemand
                );

            var result = new SharpDX.WIC.FormatConverter(factory);

            result.Initialize(
                bitmapDecoder.GetFrame(0),
                SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                SharpDX.WIC.BitmapDitherType.None,
                null,
                0.0,
                SharpDX.WIC.BitmapPaletteType.Custom);

            return(result);
        }
Esempio n. 31
0
        public IImage LoadImage(Stream stream)
        {
            var factories = Direct2DFactories.Shared;
            var d         = new WIC.BitmapDecoder(factories.WICFactory, stream, WIC.DecodeOptions.CacheOnDemand);

            WIC.BitmapSource b = d.GetFrame(0);

            var renderFormat = WIC.PixelFormat.Format32bppPBGRA;

            if (b.PixelFormat != renderFormat)
            {
                //System.Diagnostics.Debug.WriteLine ("BMP FORMAT: " + b.PixelFormat);
                var c = new WIC.FormatConverter(factories.WICFactory);
                c.Initialize(b, renderFormat);
                //System.Diagnostics.Debug.WriteLine ("CO  FORMAT: " + c.PixelFormat);
                b = c;
            }

            // Convert the BitmapSource to a Bitmap so we can allow the decoder to go out of memory
            return(new WICBitmapSourceImage(new WIC.Bitmap(factories.WICFactory, b, WIC.BitmapCreateCacheOption.CacheOnLoad), 1.0, factories));
        }
Esempio n. 32
0
        private static SharpDX.WIC.BitmapSource LoadBitmap(SharpDX.WIC.ImagingFactory2 factory, string filename)
        {
            using (var oBitmapDecoder = new SharpDX.WIC.BitmapDecoder(
                       factory,
                       filename,
                       SharpDX.WIC.DecodeOptions.CacheOnDemand
                       ))
            {
                var oFormatConverter = new SharpDX.WIC.FormatConverter(factory);

                oFormatConverter.Initialize(
                    oBitmapDecoder.GetFrame(0),
                    SharpDX.WIC.PixelFormat.Format32bppPRGBA,
                    SharpDX.WIC.BitmapDitherType.None,
                    null,
                    0.0,
                    SharpDX.WIC.BitmapPaletteType.Custom);

                return(oFormatConverter);
            }
        }
        private async Task UpdateColorTexture()
        {
            try
            {
                var encodedColorData = await _camera.Client.LatestJPEGImageAsync();

                // decode JPEG
                var memoryStream = new MemoryStream(encodedColorData);

                var stream = new WICStream(_imagingFactory, memoryStream);
                // decodes to 24 bit BGR
                var decoder           = new SharpDX.WIC.BitmapDecoder(_imagingFactory, stream, SharpDX.WIC.DecodeOptions.CacheOnLoad);
                var bitmapFrameDecode = decoder.GetFrame(0);

                // convert to 32 bpp
                var formatConverter = new FormatConverter(_imagingFactory);
                formatConverter.Initialize(bitmapFrameDecode, SharpDX.WIC.PixelFormat.Format32bppBGR);
                formatConverter.CopyPixels(nextColorData, RoomAliveToolkit.Kinect2Calibration.colorImageWidth * 4);

                UpdateColorImage(GraphicsDevice, nextColorData);
                memoryStream.Close();
                memoryStream.Dispose();
                stream.Dispose();
                decoder.Dispose();
                formatConverter.Dispose();
                bitmapFrameDecode.Dispose();
            }
            catch (System.ServiceModel.EndpointNotFoundException ex)
            {
                // TODO Message
                LiveColor = false;
                Console.WriteLine("Could not connect to Kinect for live color. Start Kinect server.");
            }
            catch (System.ServiceModel.CommunicationException)
            {
                Console.WriteLine("Connection to Kinect server for live color was lost. Restart Kinect server and the application.");
                LiveDepth = false;
            }
        }
        public static d2.Bitmap LoadBitmap(this d2.RenderTarget renderTarget, Stream stream)
        {
            var bitmapDecoder = new wic.BitmapDecoder(DXGraphicsService.FactoryImaging, stream,
                                                      wic.DecodeOptions.CacheOnDemand);

            wic.BitmapFrameDecode bitmapFrameDecode = bitmapDecoder.GetFrame(0);
            var bitmapSource = new wic.BitmapSource(bitmapFrameDecode.NativePointer);

            var formatConverter = new wic.FormatConverter(DXGraphicsService.FactoryImaging);

            formatConverter.Initialize(bitmapSource, wic.PixelFormat.Format32bppPBGRA);

            d2.Bitmap bitmap = d2.Bitmap.FromWicBitmap(renderTarget, formatConverter);

            formatConverter.Dispose();
            /* todo: check to see if I need to register to dispose of this later...  Can't comment this out because server side rendering will crash */
            //bitmapSource.Dispose();
            bitmapFrameDecode.Dispose();
            bitmapDecoder.Dispose();

            return(bitmap);
        }
Esempio n. 35
0
        /// <summary>
        /// Determines metadata for image
        /// </summary>
        /// <param name="flags">The flags.</param>
        /// <param name="decoder">The decoder.</param>
        /// <param name="frame">The frame.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">If pixel format is not supported.</exception>
        private static ImageDescription?DecodeMetadata(WICFlags flags, WIC.BitmapDecoder decoder, WIC.BitmapFrameDecode 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 == DXGI.Format.Unknown)
            {
                return(null);
            }

            return(metadata);
        }
Esempio n. 36
0
        public MeshDeviceResources(Device device, SharpDX.WIC.ImagingFactory2 imagingFactory, Mesh mesh)
        {
            this.mesh = mesh;

            // create single vertex buffer
            var stream = new DataStream(mesh.vertices.Count * Mesh.VertexPositionNormalTexture.sizeInBytes, true, true);
            stream.WriteRange(mesh.vertices.ToArray());
            stream.Position = 0;

            var vertexBufferDesc = new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage = ResourceUsage.Default,
                SizeInBytes = mesh.vertices.Count * Mesh.VertexPositionNormalTexture.sizeInBytes,
            };
            vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc);

            stream.Dispose();

            vertexBufferBinding = new VertexBufferBinding(vertexBuffer, Mesh.VertexPositionNormalTexture.sizeInBytes, 0);

            foreach (var subset in mesh.subsets)
            {
                if (subset.material.textureFilename != null)
                {
                    var decoder = new SharpDX.WIC.BitmapDecoder(imagingFactory, subset.material.textureFilename, SharpDX.WIC.DecodeOptions.CacheOnLoad);
                    var bitmapFrameDecode = decoder.GetFrame(0);

                    var stagingTextureDesc = new Texture2DDescription()
                    {
                        Width = bitmapFrameDecode.Size.Width,
                        Height = bitmapFrameDecode.Size.Height,
                        MipLevels = 1,
                        ArraySize = 1,
                        Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        Usage = ResourceUsage.Dynamic,
                        BindFlags = BindFlags.ShaderResource,
                        CpuAccessFlags = CpuAccessFlags.Write
                    };
                    var stagingTexture = new Texture2D(device, stagingTextureDesc);

                    var textureDesc = new Texture2DDescription()
                    {
                        Width = bitmapFrameDecode.Size.Width,
                        Height = bitmapFrameDecode.Size.Height,
                        MipLevels = 0,
                        ArraySize = 1,
                        Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        Usage = ResourceUsage.Default,
                        BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
                        CpuAccessFlags = CpuAccessFlags.None,
                        OptionFlags = ResourceOptionFlags.GenerateMipMaps
                    };
                    var texture = new Texture2D(device, textureDesc);

                    // convert to 32 bpp
                    var formatConverter = new FormatConverter(imagingFactory);
                    formatConverter.Initialize(bitmapFrameDecode, SharpDX.WIC.PixelFormat.Format32bppBGR);
                    var dataBox = device.ImmediateContext.MapSubresource(stagingTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
                    formatConverter.CopyPixels(dataBox.RowPitch, dataBox.DataPointer, dataBox.RowPitch * bitmapFrameDecode.Size.Height);
                    device.ImmediateContext.UnmapSubresource(stagingTexture, 0);

                    var resourceRegion = new ResourceRegion()
                    {
                        Left = 0,
                        Top = 0,
                        Right = bitmapFrameDecode.Size.Width,
                        Bottom = bitmapFrameDecode.Size.Height,
                        Front = 0,
                        Back = 1,
                    };
                    device.ImmediateContext.CopySubresourceRegion(stagingTexture, 0, resourceRegion, texture, 0);
                    var textureRV = new ShaderResourceView(device, texture);
                    device.ImmediateContext.GenerateMips(textureRV);

                    decoder.Dispose();
                    formatConverter.Dispose();
                    bitmapFrameDecode.Dispose();

                    textureRVs[subset] = textureRV;
                }
            }
        }
Esempio n. 37
0
    public bool GetThumbnail(Stream stream, int width, int height, bool cachedOnly, out byte[] imageData, out ImageType imageType)
    {
      imageData = null;
      imageType = ImageType.Unknown;
      // No support for cache
      if (cachedOnly)
        return false;

      try
      {
        if (stream.CanSeek)
          stream.Seek(0, SeekOrigin.Begin);

        // open the image file for reading
        using (var factory = new ImagingFactory2())
        using (var inputStream = new WICStream(factory, stream))
        using (var decoder = new BitmapDecoder(factory, inputStream, DecodeOptions.CacheOnLoad))
        using (var scaler = new BitmapScaler(factory))
        using (var output = new MemoryStream())
        using (var encoder = new BitmapEncoder(factory, ContainerFormatGuids.Jpeg))
        {
          // decode the loaded image to a format that can be consumed by D2D
          BitmapSource source = decoder.GetFrame(0);

          // Scale down larger images
          int sourceWidth = source.Size.Width;
          int sourceHeight = source.Size.Height;
          if (width > 0 && height > 0 && (sourceWidth > width || sourceHeight > height))
          {
            if (sourceWidth <= height)
              width = sourceWidth;

            int newHeight = sourceHeight * height / sourceWidth;
            if (newHeight > height)
            {
              // Resize with height instead
              width = sourceWidth * height / sourceHeight;
              newHeight = height;
            }

            scaler.Initialize(source, width, newHeight, BitmapInterpolationMode.Fant);
            source = scaler;
          }
          encoder.Initialize(output);

          using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
          {
            // Create image encoder
            var wicPixelFormat = PixelFormat.FormatDontCare;
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(source.Size.Width, source.Size.Height);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
            bitmapFrameEncode.WriteSource(source);
            bitmapFrameEncode.Commit();
            encoder.Commit();
          }
          imageData = output.ToArray();
          imageType = ImageType.Jpeg;
          return true;
        }
      }
      catch (Exception e)
      {
        // ServiceRegistration.Get<ILogger>().Warn("WICThumbnailProvider: Error loading bitmapSource from file data stream", e);
        return false;
      }
    }
		/// <summary>
		/// 从给定的流中加载 Direct2D 位图。
		/// </summary>
		/// <param name="stream">要加载位图的流。</param>
		/// <returns>得到的 Direct2D 位图。</returns>
		public Bitmap LoadBitmapFromStream(Stream stream)
		{
			using (BitmapDecoder decoder = new BitmapDecoder(wicFactory, stream, DecodeOptions.CacheOnLoad))
			{
				using (FormatConverter formatConverter = new FormatConverter(wicFactory))
				{
					formatConverter.Initialize(decoder.GetFrame(0), WICPixelFormat);
					return Bitmap.FromWicBitmap(this.renderTarget, formatConverter);
				}
			}
		}
Esempio n. 39
0
        //-------------------------------------------------------------------------------------
        // Load a WIC-supported file in memory
        //-------------------------------------------------------------------------------------
        public 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 = new WICStream(Factory, new DataPointer(pSource, size)))
            {
                // If the decoder is unable to decode the image, than return null
                BitmapDecoder decoder = null;
                try
                {
                    decoder = new BitmapDecoder(Factory, 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
                {
                    Utilities.FreeMemory(pSource);
                }
            }
            return image;
        }
Esempio n. 40
0
        //-------------------------------------------------------------------------------------
        // Decodes an image array, resizing/format converting as needed
        //-------------------------------------------------------------------------------------
        private static Image DecodeMultiframe(WICFlags flags, ImageDescription metadata, BitmapDecoder decoder)
        {
            var image = Image.New(metadata);

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

            for (int 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.DataPointer, pixelBuffer.BufferStride);
                        }
                        else
                        {
                            // This frame needs resizing, but not format converted
                            using (var scaler = new BitmapScaler(Factory))
                            {
                                scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags));
                                scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                            }
                        }
                    }
                    else
                    {
                        // This frame required format conversion
                        using (var converter = new FormatConverter(Factory))
                        {
                            converter.Initialize(frame, pfGuid, GetWICDither(flags), null, 0, BitmapPaletteType.Custom);

                            if (size.Width == metadata.Width && size.Height == metadata.Height)
                            {
                                converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                            }
                            else
                            {
                                // This frame needs resizing, but not format converted
                                using (var scaler = new BitmapScaler(Factory))
                                {
                                    scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags));
                                    scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                                }
                            }
                        }
                    }
                }
            }
            return image;
        }
Esempio n. 41
0
 void Initialize(s.WIC.BitmapDecoder decoder)
 {
     Frames = Enumerable.Range(0, decoder.FrameCount).Select(r => decoder.GetFrame(r).ToBitmap()).ToArray();
     // find largest frame (e.g. when loading icons)
     Control = Frames.Aggregate((x, y) => x.Size.Width > y.Size.Width || x.Size.Height > y.Size.Height ? x : y);
 }
Esempio n. 42
0
        /// <summary>
        /// Loads the specified image(s).
        /// </summary>
        /// <param name="imagingFactory">
        /// The factory for creating components for the Windows Imaging Component (WIC).
        /// </param>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="flags">Additional options.</param>
        /// <returns>A <see cref="Texture"/> representing the image(s).</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="imagingFactory"/>, <paramref name="stream"/> is <see langword="null"/>.
        /// </exception>
        public static Texture Load(ImagingFactory imagingFactory, Stream stream, WicFlags flags)
        {
            if (imagingFactory == null)
            throw new ArgumentNullException("imagingFactory");
              if (stream == null)
            throw new ArgumentNullException("stream");

              // Simple version:
              /*
              using (var bitmapDecoder = new BitmapDecoder(_imagingFactory, stream, DecodeOptions.CacheOnDemand))
              {
            // Convert the image to pre-multiplied RGBA8.
            using (var formatConverter = new FormatConverter(_imagingFactory))
            {
              formatConverter.Initialize(bitmapDecoder.GetFrame(0), PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);

              // Return a API-independent texture.
              var description = new TextureDescription
              {
            Dimension = TextureDimension.Texture2D,
            Width = formatConverter.Size.Width,
            Height = formatConverter.Size.Height,
            Depth = 1,
            MipLevels = 1,
            ArraySize = 1,
            Format = DataFormat.R8G8B8A8_UNorm
              };

              var texture = new Texture(description);
              var image = texture.Images[0];
              formatConverter.CopyPixels(image.Data, image.RowPitch);

              return texture;
            }
              }
              //*/

              // DirectXTex version:
              using (var decoder = new BitmapDecoder(imagingFactory, stream, DecodeOptions.CacheOnDemand))
              {
            var frame = decoder.GetFrame(0);

            // Get metadata.
            Guid convertGuid;
            var description = DecodeMetadata(imagingFactory, flags, decoder, frame, out convertGuid);

            if (description.ArraySize > 1 && (flags & WicFlags.AllFrames) != 0)
              return DecodeMultiframe(imagingFactory, flags, description, decoder);

            return DecodeSingleframe(imagingFactory, flags, description, convertGuid, frame);
              }
        }
Esempio n. 43
0
        /// <summary>
        /// Loads a bitmap using WIC.
        /// </summary>
        /// <param name="deviceManager"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static BitmapSource LoadBitmap(ImagingFactory factory, string filename)
        {
            var bitmapDecoder = new BitmapDecoder(
                    factory,
                    filename,
                    DecodeOptions.CacheOnDemand
                    );

                var formatConverter = new FormatConverter(factory);

                formatConverter.Initialize(
                    bitmapDecoder.GetFrame(0),
                    PixelFormat.Format32bppPRGBA,
                   BitmapDitherType.None,
                    null,
                    0.0,
                   BitmapPaletteType.Custom);

                return formatConverter;
        }
Esempio n. 44
0
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //Calculate size
            var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight);
            var newWidth = resultSize.Item1;
            var newHeight = resultSize.Item2;

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            beforeDrawImage();
            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height)));
            d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic);
            d2dContext.EndDraw();
            afterDrawImage();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var ms = new MemoryStream();

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory,ms);

            // select the image encoding format HERE
            var encoder = new wic.JpegBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(newWidth, newHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96,  0, 0, newWidth, newHeight));

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

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
Esempio n. 45
0
 public WicBitmapDecoder(ImagingFactory factory, BitmapContainerFormat format)
 {
     this.factory = factory;
     this.wicImpl = new BitmapDecoder(factory, FormatGuids[(int)format]);
 }
        /// <summary>
        /// Loads an existing image file into a SharpDX.Direct2D1.Bitmap1.
        /// </summary>
        /// <param name="filePath">Relative path to the content file.</param>
        /// <returns>Loaded bitmap.</returns>
        private SharpDX.Direct2D1.Bitmap1 LoadBitmapFromContentFile(string filePath)
        {
            SharpDX.Direct2D1.Bitmap1 newBitmap;

            // Neccessary for creating WIC objects.
            ImagingFactory imagingFactory = new ImagingFactory();
            NativeFileStream fileStream = new NativeFileStream(Package.Current.InstalledLocation.Path + filePath,
                NativeFileMode.Open, NativeFileAccess.Read);

            // Used to read the image source file.
            BitmapDecoder bitmapDecoder = new BitmapDecoder(imagingFactory, fileStream, DecodeOptions.CacheOnDemand);

            // Get the first frame of the image.
            BitmapFrameDecode frame = bitmapDecoder.GetFrame(0);

            // Convert it to a compatible pixel format.
            FormatConverter converter = new FormatConverter(imagingFactory);
            converter.Initialize(frame, SharpDX.WIC.PixelFormat.Format32bppPRGBA);

            // Create the new Bitmap1 directly from the FormatConverter.
            newBitmap = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(d2dContext, converter);

            Utilities.Dispose(ref bitmapDecoder);
            Utilities.Dispose(ref fileStream);
            Utilities.Dispose(ref imagingFactory);

            return newBitmap;
        }
Esempio n. 47
0
 private static BitmapSource Decode(ImagingFactory factory, string filename)
 {
     using (var bitmapDecoder = new BitmapDecoder(factory, filename, DecodeOptions.CacheOnDemand)
         )
         return bitmapDecoder.GetFrame(0);
 }
Esempio n. 48
0
 public WicBitmapDecoder(ImagingFactory factory, Stream stream, DecodeOptions metadataOptions)
 {
     this.factory = factory;
     this.wicImpl = new BitmapDecoder(factory, stream, metadataOptions);
 }
Esempio n. 49
0
        /// <summary>
        /// Determines metadata for image
        /// </summary>
        /// <param name="flags">The flags.</param>
        /// <param name="decoder">The decoder.</param>
        /// <param name="frame">The frame.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">If pixel format is not supported.</exception>
        private static ImageDescription? DecodeMetadata(WICFlags flags, BitmapDecoder decoder, BitmapFrameDecode 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 == DXGI.Format.Unknown)
                return null;

            return metadata;
        }
Esempio n. 50
0
 private static BitmapSource LoadBitmapSourceFromFile(ImagingFactory factory, string filename) {
     using (var bitmapDecoder = new BitmapDecoder(factory, filename, DecodeOptions.CacheOnDemand)) {
         var result = new FormatConverter(factory);
         using (var bitmapFrameDecode = bitmapDecoder.GetFrame(0)) {
             result.Initialize(bitmapFrameDecode, PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null, 0, BitmapPaletteType.Custom);
         }
         return result;
     }
 }
Esempio n. 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FastMetadataEncoder"/> class from a <see cref="BitmapDecoder"/>
 /// </summary>
 /// <param name="factory">The factory.</param>
 /// <param name="decoder">The decoder.</param>
 public FastMetadataEncoder(ImagingFactory factory, BitmapDecoder decoder) : base(IntPtr.Zero)
 {
     factory.CreateFastMetadataEncoderFromDecoder(decoder, this);
 }
Esempio n. 52
0
        private static TextureDescription DecodeMetadata(ImagingFactory imagingFactory, WicFlags flags, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid pixelFormat)
        {
            var size = frame.Size;

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

              if (description.Format == DataFormat.Unknown)
            throw new NotSupportedException("The pixel format is not supported.");

              if ((flags & WicFlags.IgnoreSrgb) == 0)
              {
            // Handle sRGB.
            #pragma warning disable 168
            try
            {
              Guid containerFormat = decoder.ContainerFormat;
              var metareader = frame.MetadataQueryReader;
              if (metareader != null)
              {
            // Check for sRGB color space metadata.
            bool sRgb = false;

            if (containerFormat == ContainerFormatGuids.Png)
            {
              // Check for sRGB chunk.
              if (metareader.GetMetadataByName("/sRGB/RenderingIntent") != null)
                sRgb = true;
            }
            else if (containerFormat == ContainerFormatGuids.Jpeg)
            {
              if (Equals(metareader.GetMetadataByName("/app1/ifd/exif/{ushort=40961}"), 1))
                sRgb = true;
            }
            else if (containerFormat == ContainerFormatGuids.Tiff)
            {
              if (Equals(metareader.GetMetadataByName("/ifd/exif/{ushort=40961}"), 1))
                sRgb = true;
            }
            else
            {
              if (Equals(metareader.GetMetadataByName("System.Image.ColorSpace"), 1))
                sRgb = true;
            }

            if (sRgb)
              description.Format = TextureHelper.MakeSRgb(description.Format);
              }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception exception)
            {
              // Some formats just don't support metadata (BMP, ICO, etc.).
            }
              }
            #pragma warning restore 168

              return description;
        }