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));
        }
Ejemplo n.º 2
0
        public static void WatermarkText(Stream imageStream, Stream outputStream, string watermark, string font = "Times New Roman", float fontSize = 30.0f, int colorARGB = TransparentWhite)
        {
            using (var wic = new WIC.ImagingFactory2())
                using (var d2d = new D2D.Factory())
                    using (var image = CreateWicImage(wic, imageStream))
                        using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
                            using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
                                using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image))
                                    using (var dwriteFactory = new DWrite.Factory())
                                        using (var brush = new D2D.SolidColorBrush(target, new Color(colorARGB)))
                                        {
                                            target.BeginDraw();
                                            {
                                                target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear);
                                                target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                                var textFormat = new DWrite.TextFormat(dwriteFactory, font, DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, fontSize)
                                                {
                                                    ParagraphAlignment = DWrite.ParagraphAlignment.Far,
                                                    TextAlignment      = DWrite.TextAlignment.Trailing,
                                                };
                                                target.DrawText(watermark, textFormat, new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                            }
                                            target.EndDraw();

                                            SaveD2DBitmap(wic, wicBitmap, outputStream);
                                        }
        }
Ejemplo n.º 3
0
 public Direct2DText()
 {
     defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                   d3d.DeviceCreationFlags.VideoSupport
                                                   | d3d.DeviceCreationFlags.BgraSupport
                                                   | d3d.DeviceCreationFlags.None); // take out the Debug flag for better performance
     d3dDevice      = defaultDevice.QueryInterface <d3d.Device1>();                 // get a reference to the Direct3D 11.1 device
     dxgiDevice     = d3dDevice.QueryInterface <dxgi.Device>();                     // get a reference to DXGI device
     d2dDevice      = new d2.Device(dxgiDevice);                                    // initialize the D2D device
     imagingFactory = new wic.ImagingFactory2();                                    // initialize the WIC factory
     d2dContext     = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
     dwFactory      = new dw.Factory();
     d2dBitmapProps = new BitmapProperties1(d2PixelFormat, dpi, dpi, BitmapOptions.Target | BitmapOptions.CannotDraw);
 }
Ejemplo n.º 4
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);
         }
     }
 }
Ejemplo n.º 5
0
        public RendererUtil()
        {
            var defaultDevice = new D3D11.Device(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport);

            d3dDevice = defaultDevice.QueryInterface<D3D11.Device1>();
            dxgiDevice = d3dDevice.QueryInterface<Device>();

            d2dFactory = new D2D.Factory(D2D.FactoryType.MultiThreaded);

            d2dDevice = new D2D.Device(dxgiDevice);
            d2dDeviceContext = new D2D.DeviceContext(d2dDevice, D2D.DeviceContextOptions.None);

            imagingFactory = new ImagingFactory2();
        }
Ejemplo n.º 6
0
        public ModernCapture()
        {
#if DEBUG
            // Check memory leaks in debug config
            Configuration.EnableObjectTracking = true;
#endif

            wrtD3D11Device = Direct3D11Helper.CreateDevice();
            d3dDevice      = Direct3D11Helper.CreateSharpDXDevice(wrtD3D11Device);
            d3dContext     = d3dDevice.ImmediateContext;
            wicFactory     = new WIC.ImagingFactory2();

            InitializeShaders();
            InitializeSharedComponents();
        }
        internal static Wic.ImagingFactory2 GetWicFactory()
        {
            object o = ThreadManage.QurayResource(Key_Class.WicIFactory);

            Wic.ImagingFactory2 fac;
            if (o == null)
            {
                fac = new Wic.ImagingFactory2();
                ThreadManage.AddResource(Key_Class.WicIFactory, fac);
            }
            else
            {
                fac = o as Wic.ImagingFactory2;
            }
            return(fac);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        private static void SaveD2DBitmap(WIC.ImagingFactory2 wic, WIC.Bitmap wicBitmap, Stream outputStream)
        {
            using (var encoder = new WIC.BitmapEncoder(wic, WIC.ContainerFormatGuids.Png))
            {
                encoder.Initialize(outputStream);
                using (var frame = new WIC.BitmapFrameEncode(encoder))
                {
                    frame.Initialize();
                    frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height);

                    var pixelFormat = wicBitmap.PixelFormat;
                    frame.SetPixelFormat(ref pixelFormat);
                    frame.WriteSource(wicBitmap);

                    frame.Commit();
                    encoder.Commit();
                }
            }
        }
        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;
        }
Ejemplo n.º 11
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);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// ファイル(リソースファイルも含む)からテクスチャーを作成する
        /// </summary>
        /// <param name="name"></param>
        /// <param name="srcFile"></param>
        /// <returns></returns>
        public static MCBaseTexture CreateTextureFromFile(Application app, string name, string srcFile)
        {
            SharpDX.Direct3D.FeatureLevel flv = app.DXDevice.FeatureLevel;
            MCTexture    tx;
            MC_FILE_TYPE fileType;

            SharpDX.WIC.ImagingFactory2 factory = new SharpDX.WIC.ImagingFactory2();
            var img = LoadBitmap(factory, srcFile, out fileType);


            tx = CreateTexture2DFromBitmap(app, img, srcFile);
            tx.CreateTxResourceView(0);
            tx.ImageFileFormat = fileType;

            img.Dispose();
            factory.Dispose();
            if (!app.ImageMgr.RegisterTexture(name, tx))
            {
                return(null);
            }
            return(tx);
        }
Ejemplo n.º 13
0
        protected RenderControllerBase(ILoader loader)
        {
            Loader = loader;
            RenderRegistry.Add("circle", CircleRender.Render);
            RenderRegistry.Add("ellipse", EllipseRender.Render);
            RenderRegistry.Add("line", LineRender.Render);
            RenderRegistry.Add("path", PathRender.Render);
            RenderRegistry.Add("polygon", PolygonRender.Render);
            RenderRegistry.Add("svg", SvgRender.Render);
            RenderRegistry.Add("use", UseRender.Render);
            RenderRegistry.Add("symbol", SymbolRender.Render);
            RenderRegistry.Add("g", GRender.Render);
            RenderRegistry.Add("text", TextRender.Render);
            RenderRegistry.Add("barcode", BarcodeRender.Render);
            RenderRegistry.Add("polyline", PolyLineRender.Render);
            RenderRegistry.Add("image", ImageRender.Render);
            RenderRegistry.Add("rect", RectangleRender.Render);
            RenderRegistry.Add("px-text", PxTextRender.Render);

            D2DFactory  = new D2D1.Factory(D2D1.FactoryType.SingleThreaded);
            WicFactory  = new WIC.ImagingFactory2();
            DwFactory   = new DW.Factory();
            FontManager = new FontManager(DwFactory);
        }
Ejemplo n.º 14
0
        public static string GenerateWallpaper(string pictureFileName, string english, string chinese, string weather)
        {
            var   wic = new WIC.ImagingFactory2();
            var   d2d = new D2D.Factory();
            float dpi = d2d.DesktopDpi.Width;

            Size2 size = new Size2(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            WIC.FormatConverter image = CreateWicImage(wic, pictureFileName);
            using (var wicBitmap = new WIC.Bitmap(wic, size.Width, size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
                using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
                    using (var dc = target.QueryInterface <D2D.DeviceContext>())
                        using (var bmpPicture = Bitmap.FromWicBitmap(target, image))
                            using (var dwriteFactory = new SharpDX.DirectWrite.Factory())
                                using (var brush = new SolidColorBrush(target, new RawColor4(255, 255, 0, 1)))
                                    using (var bmpLayer = new D2D.Bitmap1(dc, target.PixelSize,
                                                                          new D2D.BitmapProperties1(new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), dpi, dpi, BitmapOptions.Target)))
                                    {
                                        var oldTarget = dc.Target;
                                        dc.Target = bmpLayer;
                                        target.BeginDraw();
                                        {
                                            var textFormat = new DWrite.TextFormat(dwriteFactory, "Tahoma", size.Height / 27);

                                            // draw English
                                            {
                                                var textLayout = new DWrite.TextLayout(dwriteFactory, english, textFormat, target.Size.Width * 0.75f, float.MaxValue);
                                                var center     = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, (target.Size.Height - textLayout.Metrics.Height) / 2);
                                                target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush);
                                            }
                                            {
                                                var textLayout = new DWrite.TextLayout(dwriteFactory, chinese, textFormat, target.Size.Width * 0.75f, float.MaxValue);
                                                var center     = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, target.Size.Height - textLayout.Metrics.Height - size.Height / 18);
                                                target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush);
                                            }
                                            {
                                                var textLayout = new DWrite.TextLayout(dwriteFactory, weather, textFormat, target.Size.Width * 0.75f, float.MaxValue);
                                                var center     = new Vector2((target.Size.Width - textLayout.Metrics.Width) / 2, size.Height / 18 + textLayout.Metrics.Height);
                                                target.DrawTextLayout(new RawVector2(center.X, center.Y), textLayout, brush);
                                            }
                                        }
                                        target.EndDraw();

                                        // shadow
                                        var shadow = new D2D.Effects.Shadow(dc);
                                        shadow.SetInput(0, bmpLayer, new RawBool(false));

                                        dc.Target = oldTarget;
                                        target.BeginDraw();
                                        {
                                            target.DrawBitmap(bmpPicture, new SharpDX.Mathematics.Interop.RawRectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, BitmapInterpolationMode.Linear);
                                            dc.DrawImage(shadow, new RawVector2(size.Height / 150.0f, size.Height / 150.0f));
                                            dc.UnitMode = UnitMode.Pixels;
                                            target.DrawBitmap(bmpLayer, 1.0f, BitmapInterpolationMode.Linear);
                                        }
                                        target.EndDraw();

                                        string wallpaperFileName = Path.GetTempPath() + "wallpaper.png";
                                        using (var wallpaperStream = File.OpenWrite(wallpaperFileName))
                                        {
                                            SaveD2DBitmap(wic, wicBitmap, wallpaperStream);
                                            wallpaperStream.Close();
                                            return(wallpaperFileName);
                                        }
                                    }
        }
Ejemplo n.º 15
0
        static void over()
        {
            var inputPath  = "Input.png";
            var outputPath = "output.png";

            // 그래픽을 랜더링할 장비를 추가 - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.None);
            var d3dDevice  = defaultDevice.QueryInterface <d3d.Device1>(); //get a refer to the D3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device1>();    //get a refer to the DXGI device
            var d2dDevice  = new d2.Device(dxgiDevice);

            // DeviceContext를 초기화. D2D 렌더링 타겟이 될 것이고 모든 렌더링 작업을 허용
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
            var dwFactory  = new dw.Factory();


            //D2D, WIC 둘 다 지원되는 픽셀 형식 지정
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            //RGBA형식 사용
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;



            //이미지 로딩
            var imagingFactory = new wic.ImagingFactory2();
            var decoder        = new wic.PngBitmapDecoder(imagingFactory);
            var inputStream    = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read);

            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);



            //다이렉트2D가 사용할수 있도록 디코딩
            var formatConverter = new wic.FormatConverter(imagingFactory);

            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);


            //기본 이미지를 D2D이미지로 로드
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            //이미지 크기 저장
            var inputImageSize = formatConverter.Size;
            var pixelWidth     = inputImageSize.Width;
            var pixelHeight    = inputImageSize.Height;


            //Effect1 : BitpmapSource - 디코딩된 이미지 데이터를 가져오고 BitmapSource 가져오기
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);

            bitmapSourceEffect.WicBitmapSource = formatConverter;



            // Effect 2 : GaussianBlur - bitmapsource에 가우시안블러 효과 적용
            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);

            //draw a long text to show the automatic line wrapping
            var textToDraw = "sime ling text..." + "text" + "dddd";

            //create the text layout - this imroves the drawing performance for static text
            // as the glyph positions are precalculated
            //윤곽선 글꼴 데이터에서 글자 하나의 모양에 대한 기본 단위를 글리프(glyph)라고 한다
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            SharpDX.Mathematics.Interop.RawColor4 color = new SharpDX.Mathematics.Interop.RawColor4(255, 255, 255, 1);
            var textBrush = new d2.SolidColorBrush(d2dContext, color);



            //여기서부터 다시

            //render target setup

            //create the d2d bitmap description using default flags 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, new SharpDX.Mathematics.Interop.RawVector2(100f, 100f));
            d2dContext.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2(50f, 50f), textLayout, textBrush);
            d2dContext.EndDraw();

            //Image save

            //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 tream 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();

            //save
            System.Diagnostics.Process.Start(outputPath);
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
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;
      }
    }
Ejemplo n.º 18
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;
                }
            }
        }
Ejemplo n.º 19
0
		/// <summary>
		/// 将 Direct2D 位图保存到文件中。
		/// </summary>
		/// <param name="image">要保存的位图。</param>
		/// <param name="fileName">要保存的文件名。</param>
		public void SaveBitmapToFile(Bitmap image, string fileName)
		{
			using (ImagingFactory2 factory = new ImagingFactory2())
			{
				using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write))
				{
					using (BitmapEncoder encoder = new PngBitmapEncoder(factory))
					{
						encoder.Initialize(stream);
						using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder))
						{
							bitmapFrameEncode.Initialize();
							int width = image.PixelSize.Width;
							int height = image.PixelSize.Height;
							bitmapFrameEncode.SetSize(width, height);
							Guid wicPixelFormat = WICPixelFormat;
							bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
							using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice))
							{
								imageEncoder.WriteFrame(image, bitmapFrameEncode,
									new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height));
								bitmapFrameEncode.Commit();
								encoder.Commit();
							}
						}
					}
				}
			}
		}
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
0
        public static byte[] CreatePngImage(int width, int height, string text,
                                            float fontSize         = 30.0f,
                                            string font            = "Times New Roman",
                                            int lineCount          = 5,
                                            bool rotation          = false,
                                            float turbulenceAmount = 60.0f)
        {
            using (var wic = new WIC.ImagingFactory2())
                using (var d2d = new D2D.Factory())
                    using (var wicBitmap = new WIC.Bitmap(wic, width, height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
                        using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
                            using (var dwriteFactory = new DWrite.Factory())
                                using (var brush = new D2D.SolidColorBrush(target, Color.Yellow))
                                    using (var encoder = new WIC.PngBitmapEncoder(wic))

                                        using (var ms = new MemoryStream())
                                            using (var dc = target.QueryInterface <D2D.DeviceContext>())
                                                using (var bmpLayer = new D2D.Bitmap1(dc, target.PixelSize,
                                                                                      new D2D.BitmapProperties1(new D2D.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                                                                                                                d2d.DesktopDpi.Width, d2d.DesktopDpi.Height,
                                                                                                                D2D.BitmapOptions.Target)))
                                                {
                                                    var r = new Random();
                                                    encoder.Initialize(ms);

                                                    D2D.Image oldTarget = dc.Target;

                                                    {
                                                        dc.Target = bmpLayer;
                                                        dc.BeginDraw();
                                                        var textFormat = new DWrite.TextFormat(dwriteFactory, font, fontSize);
                                                        for (int charIndex = 0; charIndex < text.Length; ++charIndex)
                                                        {
                                                            using (var layout = new DWrite.TextLayout(dwriteFactory, text[charIndex].ToString(), textFormat, float.MaxValue, float.MaxValue))
                                                            {
                                                                var layoutSize = new Vector2(layout.Metrics.Width, layout.Metrics.Height);
                                                                using (var b2 = new D2D.LinearGradientBrush(dc, new D2D.LinearGradientBrushProperties
                                                                {
                                                                    StartPoint = Vector2.Zero,
                                                                    EndPoint = layoutSize,
                                                                }, new D2D.GradientStopCollection(dc, new[]
                                                                {
                                                                    new D2D.GradientStop {
                                                                        Position = 0.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f)
                                                                    },
                                                                    new D2D.GradientStop {
                                                                        Position = 1.0f, Color = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.8f)
                                                                    },
                                                                })))
                                                                {
                                                                    var position = new Vector2(charIndex * width / text.Length, r.NextFloat(0, height - layout.Metrics.Height));
                                                                    dc.Transform =
                                                                        Matrix3x2.Translation(-layoutSize / 2) *
                                                                        Matrix3x2.Skew(r.NextFloat(0, 0.5f), r.NextFloat(0, 0.5f)) *
                                                                        (rotation ? Matrix3x2.Rotation(r.NextFloat(0, (float)(Math.PI * 2))) : Matrix3x2.Identity) *
                                                                        Matrix3x2.Translation(position + layoutSize / 2);
                                                                    dc.DrawTextLayout(Vector2.Zero, layout, b2);
                                                                }
                                                            }
                                                        }
                                                        for (var i = 0; i < lineCount; ++i)
                                                        {
                                                            target.Transform = Matrix3x2.Identity;
                                                            brush.Color      = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f);
                                                            target.DrawLine(
                                                                r.NextVector2(Vector2.Zero, new Vector2(width, height)),
                                                                r.NextVector2(Vector2.Zero, new Vector2(width, height)),
                                                                brush, 3.0f);
                                                        }
                                                        target.EndDraw();
                                                    }

                                                    Color background = ColorFromHsl(r.NextFloat(0, 1), 1.0f, 0.3f);
                                                    {
                                                        dc.Target = null;
                                                        using (var displacement = new D2D.Effects.DisplacementMap(dc))
                                                        {
                                                            displacement.SetInput(0, bmpLayer, true);
                                                            displacement.Scale = turbulenceAmount;

                                                            var turbulence = new D2D.Effects.Turbulence(dc);
                                                            displacement.SetInputEffect(1, turbulence);

                                                            dc.Target = oldTarget;
                                                            dc.BeginDraw();
                                                            dc.Clear(background);
                                                            dc.DrawImage(displacement);
                                                            dc.EndDraw();

                                                            using (var frame = new WIC.BitmapFrameEncode(encoder))
                                                            {
                                                                frame.Initialize();
                                                                frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height);

                                                                var pixelFormat = wicBitmap.PixelFormat;
                                                                frame.SetPixelFormat(ref pixelFormat);
                                                                frame.WriteSource(wicBitmap);

                                                                frame.Commit();
                                                            }
                                                        }
                                                    }

                                                    encoder.Commit();
                                                    return(ms.ToArray());
                                                }
        }
        public async Task<System.IO.MemoryStream> RenderLabelToStream(
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {

            // Get stream
            var pngStream = new MemoryStream();

            using (var renderTarget = RenderLabel(
                imageWidth,
                imageHeight,
                foregroundColor,
                origin,
                textLayout,
                dpi,
                format,
                alpha))
            {

                pngStream.Position = 0;

                // Create a WIC outputstream
                using (var wicStream = new WICStream(FactoryImaging, pngStream))
                {

                    var size = renderTarget.PixelSize;

                    // Initialize a Png encoder with this stream
                    using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream))
                    {

                        // Create a Frame encoder
                        using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder))
                        {
                            wicFrameEncoder.Initialize();

                            // Create image encoder
                            ImageEncoder wicImageEncoder;
                            ImagingFactory2 factory2 = new ImagingFactory2();
                            wicImageEncoder = new ImageEncoder(factory2, D2DDevice);


                            var imgParams = new ImageParameters();
                            imgParams.PixelFormat =
                                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                                    AlphaMode.Premultiplied);

                            imgParams.PixelHeight = (int)size.Height;
                            imgParams.PixelWidth = (int)size.Width;

                            wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams);

                            //// Commit changes
                            wicFrameEncoder.Commit();
                            wicBitmapEncoder.Commit();

                            byte[] buffer = new byte[pngStream.Length];
                            pngStream.Position = 0;
                            await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length);
                        }
                    }
                }
            }

            return pngStream;
        }
Ejemplo n.º 23
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;
        }