Exemplo 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;
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        private static void DrawSmallRaw(Person person, WIC.ImagingFactory wic, D2D.Factory d2dFactory,
                                         WIC.FormatConverter converter)
        {
            var whRate       = 1.0f * converter.Size.Width / converter.Size.Height;
            var smallRawSize = new Vector2(whRate * ImageDefines.SmallRawY, ImageDefines.SmallRawY);
            var scale        = ImageDefines.SmallRawY / converter.Size.Height;

            using (var wicBitmap = new WIC.Bitmap(wic,
                                                  (int)smallRawSize.X, (int)smallRawSize.Y,
                                                  WIC.PixelFormat.Format32bppPBGRA,
                                                  WIC.BitmapCreateCacheOption.CacheOnDemand))
                using (var target = new D2D.WicRenderTarget(d2dFactory,
                                                            wicBitmap, new D2D.RenderTargetProperties()))
                    using (var bmp = D2D.Bitmap.FromWicBitmap(target, converter))
                        using (var bmpBrush = new D2D.BitmapBrush(target, bmp))
                        {
                            target.BeginDraw();
                            target.Transform = Matrix3x2.Scaling(scale, scale);
                            target.DrawBitmap(bmp, 1.0f, D2D.BitmapInterpolationMode.Linear);
                            target.EndDraw();

                            using (var file = File.Create(person.SmallRawImage))
                            {
                                WicTools.SaveD2DBitmap(wic, wicBitmap, file);
                            }
                        }
        }
        D2D1.Bitmap GetImage(IImage image)
        {
            if (image == null)
            {
                return(null);
            }

            var wbi = image as WICBitmapSourceImage;

            if (wbi != null)
            {
                Guid renderFormat = WIC.PixelFormat.Format32bppPBGRA;
                if (wbi.Bitmap.PixelFormat != renderFormat)
                {
                    //System.Diagnostics.Debug.WriteLine ("RT  FORMAT: " + renderTarget.PixelFormat.Format);
                    //System.Diagnostics.Debug.WriteLine ("BMP FORMAT: " + wbi.Bitmap.PixelFormat);
                    var c = new WIC.FormatConverter(factories.WICFactory);
                    c.Initialize(wbi.Bitmap, renderFormat);
                    //System.Diagnostics.Debug.WriteLine ("CO  FORMAT: " + c.PixelFormat);
                    return(D2D1.Bitmap.FromWicBitmap(renderTarget, c));
                }
                else
                {
                    return(D2D1.Bitmap.FromWicBitmap(renderTarget, wbi.Bitmap));
                }
            }

            throw new NotSupportedException("Image type " + image.GetType() + " not supported");
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
 public void Dispose()
 {
     FormatConverter?.Dispose();
     FormatConverter = null;
     Image?.Dispose();
     Image = null;
 }
Exemplo n.º 9
0
 public static D2D1.Bitmap CreateD2DBitmap(Wic.FormatConverter fconv)
 {
     D2D1.Bitmap map;
     lock (DX_Core.D2D)
         map = D2D1.Bitmap.FromWicBitmap(DX_Core.D2D.d2dContext, fconv);
     return(map);
 }
Exemplo n.º 10
0
        public D3D11Renderer(ObservableVideoTrack videoTrack, RendererOptions options)
            : base(videoTrack, options)
        {
            // _factoryDWrite = new DWrite.Factory(DWrite.FactoryType.Shared);

            var device2D = new D2D1.Device(DeviceDXGI, new D2D1.CreationProperties
            {
                DebugLevel    = D2D1.DebugLevel.Warning,
                ThreadingMode = D2D1.ThreadingMode.MultiThreaded,
                Options       = D2D1.DeviceContextOptions.None
            });

            _context2D = new D2D1.DeviceContext(device2D, D2D1.DeviceContextOptions.None);

            // Load the background image
            using (var factoryWic = new WIC.ImagingFactory2())
                using (var decoder = new WIC.JpegBitmapDecoder(factoryWic))
                    using (var inputStream = new WIC.WICStream(factoryWic, "background-small.jpg", NativeFileAccess.Read))
                        using (var formatConverter = new WIC.FormatConverter(factoryWic))
                            using (var bitmapScaler = new WIC.BitmapScaler(factoryWic))
                            {
                                decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad);
                                formatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPBGRA);
                                bitmapScaler.Initialize(formatConverter, VideoFrameWidth, VideoFrameHeight,
                                                        WIC.BitmapInterpolationMode.Fant);
                                _backgroundBitmap = D2D1.Bitmap1.FromWicBitmap(_context2D, bitmapScaler);
                            }

            // Create render target
            _ballEllipse = new D2D1.Ellipse {
                RadiusX = VideoFrameWidth / 20f, RadiusY = VideoFrameWidth / 20f
            };

            _ballBrush = new D2D1.SolidColorBrush(_context2D, new RawColor4(1f, 1f, 0f, 1f));
        }
Exemplo n.º 11
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));
                     }
 }
Exemplo n.º 12
0
        //-------------------------------------------------------------------------------------
        // Encodes a single frame
        //-------------------------------------------------------------------------------------
        private static void EncodeImage(PixelBuffer image, WICFlags flags, WIC.BitmapFrameEncode frame)
        {
            Guid pfGuid;

            if (!ToWIC(image.Format, out pfGuid))
            {
                throw new NotSupportedException("Format not supported");
            }

            frame.Initialize();
            frame.SetSize(image.Width, image.Height);
            frame.SetResolution(72, 72);
            Guid targetGuid = pfGuid;

            frame.SetPixelFormat(ref targetGuid);

            if (targetGuid != pfGuid)
            {
                using (var source = new WIC.Bitmap(Factory, image.Width, image.Height, pfGuid, new SDX.DataRectangle(image.DataPointer, image.RowStride), image.BufferStride))
                {
                    using (var converter = new WIC.FormatConverter(Factory))
                    {
                        using (var palette = new WIC.Palette(Factory))
                        {
                            palette.Initialize(source, 256, true);
                            converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, WIC.BitmapPaletteType.Custom);

                            int bpp = GetBitsPerPixel(targetGuid);
                            if (bpp == 0)
                            {
                                throw new NotSupportedException("Unable to determine the Bpp for the target format");
                            }

                            int rowPitch   = (image.Width * bpp + 7) / 8;
                            int slicePitch = rowPitch * image.Height;

                            var temp = SDX.Utilities.AllocateMemory(slicePitch);
                            try
                            {
                                converter.CopyPixels(rowPitch, temp, slicePitch);
                                frame.Palette = palette;
                                frame.WritePixels(image.Height, temp, rowPitch, slicePitch);
                            }
                            finally
                            {
                                SDX.Utilities.FreeMemory(temp);
                            }
                        }
                    }
                }
            }
            else
            {
                // No conversion required
                frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride);
            }

            frame.Commit();
        }
Exemplo n.º 13
0
 protected override sd.Bitmap CreateDrawableBitmap(sd.RenderTarget target)
 {
     using (var converter = new sw.FormatConverter(SDFactory.WicImagingFactory))
     {
         converter.Initialize(Control, sw.PixelFormat.Format32bppPBGRA);
         var bmp = new sw.Bitmap(SDFactory.WicImagingFactory, converter, sw.BitmapCreateCacheOption.CacheOnLoad);
         return(sd.Bitmap.FromWicBitmap(target, bmp));
     }
 }
Exemplo n.º 14
0
        public SharpDX.Direct2D1.Bitmap GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget)
        {
            if (this.direct2D == null)
            {
                FormatConverter converter = new FormatConverter(this.factory);
                converter.Initialize(this.WicImpl, PixelFormat.Format32bppPBGRA);
                this.direct2D = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTarget, converter);
            }

            return this.direct2D;
        }
Exemplo n.º 15
0
        public PngImageResource(WIC.ImagingFactory imagingFactory, string path)
        {
            using (var decoder = new WIC.PngBitmapDecoder(imagingFactory))
            {
                using (var inputStream = new WIC.WICStream(imagingFactory, path, NativeFileAccess.Read))
                    decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad);

                FormatConverter = new WIC.FormatConverter(imagingFactory);
                FormatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPRGBA);
            }
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
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));
                 }
 }
Exemplo n.º 18
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);
            }
        }
Exemplo n.º 19
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));
        }
Exemplo n.º 20
0
 private static WIC.FormatConverter CreateWicImage(WIC.ImagingFactory2 wic, Stream imageStream)
 {
     using (var decoder = new WIC.PngBitmapDecoder(wic))
     {
         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);
         }
     }
 }
Exemplo n.º 21
0
 public static WIC.FormatConverter CreateWicImage(WIC.ImagingFactory wic, string filename)
 {
     using (var decoder = new WIC.JpegBitmapDecoder(wic))
         using (var decodeStream = new WIC.WICStream(wic, filename, NativeFileAccess.Read))
         {
             decoder.Initialize(decodeStream, WIC.DecodeOptions.CacheOnDemand);
             using (var decodeFrame = decoder.GetFrame(0))
             {
                 var converter = new WIC.FormatConverter(wic);
                 converter.Initialize(decodeFrame, WIC.PixelFormat.Format32bppPBGRA);
                 return(converter);
             }
         }
 }
Exemplo n.º 22
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));
        }
        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);
        }
Exemplo 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);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Function to convert a WIC bitmap to a System.Drawing.Image
        /// </summary>
        /// <param name="bitmap">Bitmap to convert.</param>
        /// <param name="format">Pixel format to use.</param>
        /// <returns>The converted bitmap.</returns>
        public Image CreateGDIImageFromWICBitmap(WIC.Bitmap bitmap, PixelFormat format)
        {
            Bitmap     result           = null;
            BitmapData lockData         = null;
            Guid       conversionFormat = GetGUID(format);

            if (conversionFormat == Guid.Empty)
            {
                throw new GorgonException(GorgonResult.FormatNotSupported,
                                          string.Format(Resources.GORGFX_FORMAT_NOT_SUPPORTED, format));
            }

            try
            {
                // Create the new bitmap.
                result = new Bitmap(bitmap.Size.Width, bitmap.Size.Height, format);

                lockData = result.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.WriteOnly, format);

                // We need to convert, so copy using the format converter.
                if (bitmap.PixelFormat != conversionFormat)
                {
                    using (var converter = new WIC.FormatConverter(Factory))
                    {
                        converter.Initialize(bitmap, conversionFormat, WIC.BitmapDitherType.None, null, 0, WIC.BitmapPaletteType.Custom);
                        converter.CopyPixels(lockData.Stride, lockData.Scan0, lockData.Stride * lockData.Height);
                    }
                }
                else
                {
                    // Otherwise, copy it all in one shot.
                    bitmap.CopyPixels(lockData.Stride, lockData.Scan0, lockData.Stride * lockData.Height);
                }

                return(result);
            }
            finally
            {
                if (lockData != null)
                {
                    result.UnlockBits(lockData);
                }
            }
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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);
        }
        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);
        }
        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;
        }
Exemplo n.º 30
0
        //-------------------------------------------------------------------------------------
        // Decodes a single frame
        //-------------------------------------------------------------------------------------
        private static Image DecodeSingleFrame(WICFlags flags, ImageDescription metadata, Guid convertGUID, WIC.BitmapFrameDecode frame)
        {
            var image = Image.New(metadata);

            var pixelBuffer = image.PixelBuffer[0];

            if (convertGUID == Guid.Empty)
            {
                frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
            }
            else
            {
                using (var converter = new WIC.FormatConverter(Factory))
                {
                    converter.Initialize(frame, convertGUID, GetWICDither(flags), null, 0, WIC.BitmapPaletteType.Custom);
                    converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                }
            }

            return(image);
        }
Exemplo 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));
        }
Exemplo 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);
            }
        }
        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);
        }
Exemplo n.º 34
0
        private static void DrawPsd(Person person, WIC.ImagingFactory wic, D2D.Factory d2dFactory,
                                    WIC.FormatConverter converter)
        {
            using (var wicBitmap = new WIC.Bitmap(wic,
                                                  (int)ImageDefines.Size, (int)ImageDefines.Size,
                                                  WIC.PixelFormat.Format32bppPBGRA,
                                                  WIC.BitmapCreateCacheOption.CacheOnDemand))
                using (var target = new D2D.WicRenderTarget(d2dFactory,
                                                            wicBitmap, new D2D.RenderTargetProperties()))
                    using (var color = new D2D.SolidColorBrush(target, SexColor[person.Sex]))
                        using (var bmp = D2D.Bitmap.FromWicBitmap(target, converter))
                            using (var bmpBrush = new D2D.BitmapBrush(target, bmp))
                            {
                                target.BeginDraw();
                                var offset = (ImageDefines.Size - ImageDefines.RealSize) / 2;
                                bmpBrush.Transform = Matrix3x2.Scaling(
                                    ImageDefines.RealSize / bmp.Size.Width,
                                    ImageDefines.RealSize / (bmp.Size.Height - 497.0f))
                                                     * Matrix3x2.Translation(offset, offset);
                                target.FillEllipse(new D2D.Ellipse(
                                                       new Vector2(ImageDefines.Size / 2.0f, ImageDefines.Size / 2.0f),
                                                       ImageDefines.RealSize / 2.0f,
                                                       ImageDefines.RealSize / 2.0f),
                                                   bmpBrush);
                                target.DrawEllipse(new D2D.Ellipse(
                                                       new Vector2(ImageDefines.Size / 2.0f, ImageDefines.Size / 2.0f),
                                                       ImageDefines.RealSize / 2.0f,
                                                       ImageDefines.RealSize / 2.0f),
                                                   color, ImageDefines.LineWidth);
                                target.EndDraw();

                                using (var file = File.Create(person.PsdImage))
                                {
                                    WicTools.SaveD2DBitmap(wic, wicBitmap, file);
                                }
                            }
        }
Exemplo n.º 35
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;
        }
        /// <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;
        }
Exemplo n.º 37
0
        D2D1.Bitmap GetImage(IImage image)
        {
            if (image == null)
                return null;

            var wbi = image as WICBitmapSourceImage;
            if (wbi != null) {
                Guid renderFormat = WIC.PixelFormat.Format32bppPBGRA;
                if (wbi.Bitmap.PixelFormat != renderFormat) {
                    //System.Diagnostics.Debug.WriteLine ("RT  FORMAT: " + renderTarget.PixelFormat.Format);
                    //System.Diagnostics.Debug.WriteLine ("BMP FORMAT: " + wbi.Bitmap.PixelFormat);
                    var c = new WIC.FormatConverter (factories.WICFactory);
                    c.Initialize (wbi.Bitmap, renderFormat);
                    //System.Diagnostics.Debug.WriteLine ("CO  FORMAT: " + c.PixelFormat);
                    return D2D1.Bitmap.FromWicBitmap (renderTarget, c);
                }
                else {
                    return D2D1.Bitmap.FromWicBitmap (renderTarget, wbi.Bitmap);
                }
            }

            throw new NotSupportedException ("Image type " + image.GetType () + " not supported");
        }
Exemplo n.º 38
0
        //-------------------------------------------------------------------------------------
        // Encodes a single frame
        //-------------------------------------------------------------------------------------
        private static void EncodeImage( PixelBuffer image, WICFlags flags, BitmapFrameEncode frame)
        {
            Guid pfGuid;
            if (! ToWIC(image.Format, out pfGuid))
                throw new NotSupportedException("Format not supported");

            frame.Initialize();
            frame.SetSize(image.Width, image.Height);
            frame.SetResolution(72, 72);
            Guid targetGuid = pfGuid;
            frame.SetPixelFormat(ref targetGuid);

            if (targetGuid != pfGuid)
            {
                using (var source = new Bitmap(Factory, image.Width, image.Height, pfGuid, new DataRectangle(image.DataPointer, image.RowStride), image.BufferStride))
                {
                    using (var converter = new FormatConverter(Factory))
                    {
                        using (var palette = new Palette(Factory))
                        {
                            palette.Initialize(source, 256, true);
                            converter.Initialize(source, targetGuid, GetWICDither(flags), palette, 0, BitmapPaletteType.Custom);

                            int bpp = GetBitsPerPixel(targetGuid);
                            if (bpp == 0) throw new NotSupportedException("Unable to determine the Bpp for the target format");

                            int rowPitch = (image.Width * bpp + 7) / 8;
                            int slicePitch = rowPitch * image.Height;

                            var temp = Utilities.AllocateMemory(slicePitch);
                            try
                            {
                                converter.CopyPixels(rowPitch, temp, slicePitch);
                                frame.Palette = palette;
                                frame.WritePixels(image.Height, temp, rowPitch, slicePitch);
                            }
                            finally
                            {
                                Utilities.FreeMemory(temp);
                            }
                        }
                    }
                }
            }
            else
            {
                // No conversion required
                frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride);
            }

            frame.Commit();
        }
Exemplo n.º 39
0
        private static Texture DecodeSingleframe(ImagingFactory imagingFactory, WicFlags flags, TextureDescription description, Guid convertGuid, BitmapFrameDecode frame)
        {
            var texture = new Texture(description);
              var image = texture.Images[0];

              if (convertGuid == Guid.Empty)
              {
            frame.CopyPixels(image.Data, image.RowPitch);
              }
              else
              {
            using (var converter = new FormatConverter(imagingFactory))
            {
              converter.Initialize(frame, convertGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
              converter.CopyPixels(image.Data, image.RowPitch);
            }
              }

              return texture;
        }
Exemplo n.º 40
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;
        }
Exemplo n.º 41
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;
     }
 }
Exemplo n.º 42
0
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // 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.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            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.PngBitmapDecoder(imagingFactory); // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading
            decoder.Initialize(inputStream, 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);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

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

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);
            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // 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);

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

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

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

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath);

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

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

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            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, pixelWidth, pixelHeight));

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

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

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
Exemplo n.º 43
0
        private static void FlushCurrentFrame(GifBitmapEncoder encoder,
            ImagingFactory factory,
            BitmapFrame bitmap)
        {
            // nothing to flush.
            if (bitmap == null)
            {
                return;
            }

            using (var frameEncoder = new BitmapFrameEncode(encoder))
            {
                frameEncoder.Initialize();
                frameEncoder.SetSize(bitmap.Data.Width, bitmap.Data.Height);
                frameEncoder.SetResolution(bitmap.Data.HorizontalResolution, bitmap.Data.VerticalResolution);

                // embed frame metadata.
                var metadataWriter = frameEncoder.MetadataQueryWriter;
                metadataWriter.SetMetadataByName("/grctlext/Delay", Convert.ToUInt16(bitmap.Delay/100));
                metadataWriter.SetMetadataByName("/imgdesc/Left", Convert.ToUInt16(bitmap.XPos));
                metadataWriter.SetMetadataByName("/imgdesc/Top", Convert.ToUInt16(bitmap.YPos));
                metadataWriter.SetMetadataByName("/imgdesc/Width", Convert.ToUInt16(bitmap.Data.Width));
                metadataWriter.SetMetadataByName("/imgdesc/Height", Convert.ToUInt16(bitmap.Data.Height));

                using (var bitmapSource = new WicBitmap(
                    factory,
                    bitmap.Data,
                    BitmapAlphaChannelOption.UsePremultipliedAlpha))
                {
                    var converter = new FormatConverter(factory);
                    converter.Initialize(bitmapSource,
                        PixelFormat.Format8bppIndexed,
                        BitmapDitherType.Solid,
                        null,
                        0.8,
                        BitmapPaletteType.MedianCut);

                    frameEncoder.WriteSource(converter);
                    frameEncoder.Commit();
                }
            }
        }
Exemplo n.º 44
0
		/// <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);
				}
			}
		}
Exemplo n.º 45
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;
                }
            }
        }
Exemplo n.º 46
0
        //-------------------------------------------------------------------------------------
        // Decodes a single frame
        //-------------------------------------------------------------------------------------
        private static Image DecodeSingleFrame(WICFlags flags, ImageDescription metadata, Guid convertGUID, BitmapFrameDecode frame)
        {
            var image = Image.New(metadata);

            var pixelBuffer = image.PixelBuffer[0];

            if (convertGUID == Guid.Empty)
            {
                frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
            }
            else
            {
                using (var converter = new FormatConverter(Factory))
                {
                    converter.Initialize(frame, convertGUID, GetWICDither(flags), null, 0, BitmapPaletteType.Custom);
                    converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                }
            }

            return image;
        }
Exemplo n.º 47
0
        //-------------------------------------------------------------------------------------
        // Decodes an image array, resizing/format converting as needed
        //-------------------------------------------------------------------------------------
        private static Image DecodeMultiframe(WICFlags flags, ImageDescription metadata, WIC.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 WIC.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 WIC.FormatConverter(Factory))
                        {
                            converter.Initialize(frame, pfGuid, GetWICDither(flags), null, 0, WIC.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 WIC.BitmapScaler(Factory))
                                {
                                    scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags));
                                    scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride);
                                }
                            }
                        }
                    }
                }
            }
            return(image);
        }
Exemplo n.º 48
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;
        }
Exemplo n.º 49
0
 private static FormatConverter Convert(ImagingFactory factory, BitmapSource source)
 {
     var formatConverter = new FormatConverter(factory);
     formatConverter.Initialize(source, PixelFormat.Format32bppPRGBA, BitmapDitherType.None, null,
         0.0, BitmapPaletteType.Custom);
     return formatConverter;
 }
Exemplo n.º 50
0
        private static void EncodeImage(ImagingFactory imagingFactory, Image image, WicFlags flags, Guid containerFormat, BitmapFrameEncode frame)
        {
            Guid pfGuid = ToWic(image.Format, false);

              frame.Initialize();
              frame.SetSize(image.Width, image.Height);
              frame.SetResolution(72, 72);
              Guid targetGuid = pfGuid;
              frame.SetPixelFormat(ref targetGuid);

              EncodeMetadata(frame, containerFormat, image.Format);

              if (targetGuid != pfGuid)
              {
            // Conversion required to write.
            GCHandle handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
            using (var source = new Bitmap(imagingFactory, image.Width, image.Height, pfGuid, new DataRectangle(handle.AddrOfPinnedObject(), image.RowPitch), image.Data.Length))
            {
              using (var converter = new FormatConverter(imagingFactory))
              {
            if (!converter.CanConvert(pfGuid, targetGuid))
              throw new NotSupportedException("Format conversion is not supported.");

            converter.Initialize(source, targetGuid, GetWicDither(flags), null, 0, BitmapPaletteType.Custom);
            frame.WriteSource(converter, new Rectangle(0, 0, image.Width, image.Height));
              }
            }

            handle.Free();
              }
              else
              {
            // No conversion required.
            frame.WritePixels(image.Height, image.RowPitch, image.Data);
              }

              frame.Commit();
        }