Exemplo n.º 1
0
        public WriteableBitmap getWriteableBitmap()
        {
            WriteableBitmap wbmp = new WriteableBitmap((int)(_symbolBounds.Width), (int)(_symbolBounds.Height));

            _crt.GetPixelBytes(wbmp.PixelBuffer);
            return(wbmp);
        }
Exemplo n.º 2
0
        public Task <InMemoryRandomAccessStream> ConvertInkToPng(Rect viewport, double scale, IEnumerable <InkStroke> strokes, double minStrokeThickness = 0)
        {
            var device         = CanvasDevice.GetSharedDevice();
            var dpi            = DisplayInformation.GetForCurrentView().LogicalDpi;
            var scaledViewport = viewport.Scale(scale);
            var renderTarget   = new CanvasRenderTarget(device, (float)scaledViewport.Width, (float)scaledViewport.Height, dpi);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                var inkStrokes = strokes
                                 .Where(x => x.BoundingRect.IsIntersect(viewport))
                                 .Select(x =>
                {
                    var stroke             = x.Translate(-viewport.Left, -viewport.Top);
                    stroke.PointTransform *= Matrix3x2.CreateScale((float)scale);
                    var da  = stroke.DrawingAttributes;
                    var sz  = da.Size.Scale(scale);
                    da.Size = new Size(Math.Max(minStrokeThickness, sz.Width), Math.Max(minStrokeThickness, sz.Height));
                    stroke.DrawingAttributes = da;
                    return(stroke);
                });
                Render(ds, inkStrokes);
            }
            var pixels = renderTarget.GetPixelBytes();

            return(ConvertPixelsToPng(pixels, (int)renderTarget.SizeInPixels.Width, (int)renderTarget.SizeInPixels.Height));
        }
Exemplo n.º 3
0
        public async Task <SoftwareBitmap> SaveToBitmap(InkStrokeContainer ink)
        {
            ICanvasResourceCreator device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget     renderTarget = new CanvasRenderTarget(device, Image.PixelWidth, Image.PixelHeight, 96);

            renderTarget.SetPixelBytes(new byte[Image.PixelWidth * 4 * Image.PixelHeight]);
            byte[] imageBytes = new byte[4 * Image.PixelWidth * Image.PixelHeight];
            using (var ds = renderTarget.CreateDrawingSession())
            {
                Image.CopyToBuffer(imageBytes.AsBuffer());
                var win2dRenderedBitmap = CanvasBitmap.CreateFromBytes(
                    device,
                    imageBytes,
                    Image.PixelWidth,
                    Image.PixelHeight,
                    Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    96.0f);
                ds.DrawImage(win2dRenderedBitmap);
                IReadOnlyList <InkStroke> inklist = ink.GetStrokes();
                ds.DrawInk(inklist);
            }
            var             inkpixel = renderTarget.GetPixelBytes();
            WriteableBitmap bmp      = new WriteableBitmap((int)Image.PixelWidth, (int)Image.PixelHeight);
            Stream          s        = bmp.PixelBuffer.AsStream();

            s.Seek(0, SeekOrigin.Begin);
            s.Write(inkpixel, 0, (int)Image.PixelWidth * 4 * (int)Image.PixelHeight);
            s.Position = 0;
            await s.ReadAsync(imageBytes, 0, (int)s.Length);

            Image.CopyFromBuffer(imageBytes.AsBuffer());
            return(Image);
        }
Exemplo n.º 4
0
        public static SoftwareBitmap CropAndResize(this SoftwareBitmap softwareBitmap, Rect bounds, float newWidth, float newHeight)
        {
            var resourceCreator = CanvasDevice.GetSharedDevice();

            using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
                using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, newWidth, newHeight, canvasBitmap.Dpi))
                    using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                        using (var scaleEffect = new ScaleEffect())
                            using (var cropEffect = new CropEffect())
                                using (var atlasEffect = new AtlasEffect())
                                {
                                    drawingSession.Clear(Colors.White);

                                    cropEffect.SourceRectangle = bounds;
                                    cropEffect.Source          = canvasBitmap;

                                    atlasEffect.SourceRectangle = bounds;
                                    atlasEffect.Source          = cropEffect;

                                    scaleEffect.Source = atlasEffect;
                                    scaleEffect.Scale  = new System.Numerics.Vector2(newWidth / (float)bounds.Width, newHeight / (float)bounds.Height);
                                    drawingSession.DrawImage(scaleEffect);
                                    drawingSession.Flush();

                                    return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied));
                                }
        }
Exemplo n.º 5
0
        public static async Task <SoftwareBitmap> ResizeSoftwareBitmap(SoftwareBitmap softwareBitmap, double scaleFactor)
        {
            var resourceCreator    = CanvasDevice.GetSharedDevice();
            var canvasBitmap       = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap);
            var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, (int)(softwareBitmap.PixelWidth * scaleFactor), (int)(softwareBitmap.PixelHeight * scaleFactor), 96);

            using (var cds = canvasRenderTarget.CreateDrawingSession())
            {
                cds.DrawImage(canvasBitmap, canvasRenderTarget.Bounds);
            }

            var pixelBytes = canvasRenderTarget.GetPixelBytes();

            var writeableBitmap = new WriteableBitmap((int)(softwareBitmap.PixelWidth * scaleFactor), (int)(softwareBitmap.PixelHeight * scaleFactor));

            using (var stream = writeableBitmap.PixelBuffer.AsStream())
            {
                await stream.WriteAsync(pixelBytes, 0, pixelBytes.Length);
            }

            var scaledSoftwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Rgba16, (int)(softwareBitmap.PixelWidth * scaleFactor), (int)(softwareBitmap.PixelHeight * scaleFactor));

            scaledSoftwareBitmap.CopyFromBuffer(writeableBitmap.PixelBuffer);

            return(scaledSoftwareBitmap);
        }
        public async Task <SoftwareBitmap> SaveToBitmap(InkStrokeContainer ink)
        {
            ICanvasResourceCreator device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget     renderTarget = new CanvasRenderTarget(device, Width, Height, 96);
            var src = new byte[Width * 4 * Height];

            for (int index = 0; index < src.Length; ++index)
            {
                src[index] = 255;
            }
            renderTarget.SetPixelBytes(src);
            byte[] imageBytes = new byte[4 * Width * Height];
            using (var ds = renderTarget.CreateDrawingSession())
            {
                IReadOnlyList <InkStroke> inklist = ink.GetStrokes();
                ds.DrawInk(inklist);
            }
            var             inkpixel = renderTarget.GetPixelBytes();
            WriteableBitmap bmp      = new WriteableBitmap(Width, Height);
            Stream          s        = bmp.PixelBuffer.AsStream();

            s.Seek(0, SeekOrigin.Begin);
            s.Write(inkpixel, 0, Width * 4 * Height);
            s.Position = 0;
            await s.ReadAsync(imageBytes, 0, (int)s.Length);

            SoftwareBitmap result = new SoftwareBitmap(BitmapPixelFormat.Bgra8, Width, Height, BitmapAlphaMode.Premultiplied);

            result.CopyFromBuffer(imageBytes.AsBuffer());
            return(result);
        }
Exemplo n.º 7
0
        // crop
        public SoftwareBitmap Crop(SoftwareBitmap softwareBitmap, Rect bounds)
        {
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8);
            }

            var resourceCreator = CanvasDevice.GetSharedDevice();

            using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
                using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, (float)bounds.Width, (float)bounds.Width, canvasBitmap.Dpi))
                    using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                        using (var cropEffect = new CropEffect())
                            using (var atlasEffect = new AtlasEffect())
                            {
                                drawingSession.Clear(Colors.White);

                                cropEffect.SourceRectangle = bounds;
                                cropEffect.Source          = canvasBitmap;

                                atlasEffect.SourceRectangle = bounds;
                                atlasEffect.Source          = cropEffect;

                                drawingSession.DrawImage(atlasEffect);
                                drawingSession.Flush();

                                return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)bounds.Width, (int)bounds.Width, BitmapAlphaMode.Premultiplied));
                            }
        }
Exemplo n.º 8
0
        public static CanvasRenderTarget GenImage(int width, int height, Color clr, byte alpha)
        {
            CanvasDevice device = CanvasDevice.GetSharedDevice();

            CanvasRenderTarget offscreen = new CanvasRenderTarget(device, width, height, 96, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                                  CanvasAlphaMode.Premultiplied);

            byte[] pixels = offscreen.GetPixelBytes();

            if (pixels == null)
            {
                return(null);
            }

            uint col    = 0;
            uint stride = offscreen.SizeInPixels.Width;

            for (uint row = 0; row < offscreen.SizeInPixels.Height; ++row)
            {
                uint total_row_len = (uint)(row * stride);
                for (col = 0; col < offscreen.SizeInPixels.Width; ++col)
                {
                    uint index = (total_row_len + col) * 4;

                    pixels[index + 3] = alpha;
                    pixels[index + 2] = clr.R;
                    pixels[index + 1] = clr.G;
                    pixels[index]     = clr.B;
                }
            }
            offscreen.SetPixelBytes(pixels);

            return(offscreen);
        }
Exemplo n.º 9
0
 public void RefreshImage()
 {
     if (renderTarget != null)
     {
         var bytes  = renderTarget.GetPixelBytes();
         var bitmap = SoftwareBitmap.CreateCopyFromBuffer(bytes.AsBuffer(), BitmapPixelFormat.Bgra8, (int)renderTarget.Size.Width, (int)renderTarget.Size.Height);
         ClipImage.Image.OnNext(new ImageData {
             SoftwareBitmap = bitmap, Bytes = bytes
         });
     }
 }
        public static SoftwareBitmap DrawInk(this IList <InkStroke> strokes, double targetWidth = 0, double targetHeight = 0, float rotation = 0, Color?backgroundColor = null)
        {
            if (strokes == null)
            {
                throw new ArgumentNullException($"{nameof(strokes)} cannot be null");
            }

            var boundingBox = strokes.GetBoundingBox();

            if (targetWidth == 0)
            {
                targetWidth = DEFAULT_WIDTH;
            }

            if (targetHeight == 0)
            {
                targetHeight = DEFAULT_HEIGHT;
            }

            if (backgroundColor == null)
            {
                backgroundColor = Colors.White;
            }

            var scale = CalculateScale(boundingBox, targetWidth, targetHeight);

            var scaledStrokes = ScaleAndTransformStrokes(strokes, scale, rotation);

            WriteableBitmap writeableBitmap = null;
            CanvasDevice    device          = CanvasDevice.GetSharedDevice();

            using (CanvasRenderTarget offscreen = new CanvasRenderTarget(device, (float)targetWidth, (float)targetHeight, 96))
            {
                using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
                {
                    ds.Units = CanvasUnits.Pixels;
                    ds.Clear(backgroundColor.Value);
                    ds.DrawInk(scaledStrokes);
                }

                writeableBitmap = new WriteableBitmap((int)offscreen.SizeInPixels.Width, (int)offscreen.SizeInPixels.Height);
                offscreen.GetPixelBytes().CopyTo(writeableBitmap.PixelBuffer);
            }

            SoftwareBitmap inkBitmap = SoftwareBitmap.CreateCopyFromBuffer(
                writeableBitmap.PixelBuffer,
                BitmapPixelFormat.Bgra8,
                writeableBitmap.PixelWidth,
                writeableBitmap.PixelHeight,
                BitmapAlphaMode.Premultiplied
                );

            return(inkBitmap);
        }
Exemplo n.º 11
0
        public static SoftwareBitmap GetSoftwareBitmap(this InkCanvas canvas, IEnumerable <InkStroke> strokes = null)
        {
            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)canvas.ActualWidth, (int)canvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
                ds.DrawInk(strokes ?? canvas.InkPresenter.StrokeContainer.GetStrokes(), true);
            }

            return(SoftwareBitmap.CreateCopyFromBuffer(renderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)canvas.ActualWidth, (int)canvas.ActualHeight, BitmapAlphaMode.Premultiplied));
        }
Exemplo n.º 12
0
        private async void MediaPlayer_VideoFrameAvailableAsync(MediaPlayer sender, object args)
        {
            if (!isRenderringFinished)
            {
                return;
            }
            isRenderringFinished = false;
            //CanvasDevice canvasDevice = CanvasDevice.GetSharedDevice();

            if (frameServerDest == null)
            {
                frameServerDest = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)sender.PlaybackSession.NaturalVideoWidth, (int)sender.PlaybackSession.NaturalVideoHeight, BitmapAlphaMode.Ignore);
            }
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                canvasImageSource  = new CanvasImageSource(canvasDevice, (int)sender.PlaybackSession.NaturalVideoWidth, (int)sender.PlaybackSession.NaturalVideoWidth, DisplayInformation.GetForCurrentView().LogicalDpi);//96);
                OutputImage.Source = canvasImageSource;

                try
                {
                    using (CanvasBitmap inputBitmap = CanvasBitmap.CreateFromSoftwareBitmap(canvasDevice, frameServerDest))
                    //using (CanvasDrawingSession ds = canvasImageSource.CreateDrawingSession(Colors.Black))
                    {
                        sender.CopyFrameToVideoSurface(inputBitmap);

                        using (var cds = canvasRenderTarget.CreateDrawingSession())
                        {
                            cds.DrawImage(inputBitmap, canvasRenderTarget.Bounds);
                        }

                        var pixelBytes = canvasRenderTarget.GetPixelBytes();

                        if (pixelBytes[40] == 0)
                        {
                            System.Diagnostics.Debug.WriteLine("fuckzero");
                        }

                        var boxes = await DetectObjectPoseFromImagePixelsAsync(pixelBytes).ConfigureAwait(true);

                        DrawBoxes(inputBitmap, boxes, canvasImageSource);
                        //ds.DrawImage(inputBitmap);
                    }
                }
                catch (Exception exception)
                {
                    System.Diagnostics.Debug.WriteLine(exception.Message);
                }
            });

            isRenderringFinished = true;
        }
Exemplo n.º 13
0
        //流转图
        public static WriteableBitmap BuffertoBitmap(CanvasRenderTarget crt)
        {
            byte[] buffer = crt.GetPixelBytes();
            int    Width  = (int)crt.SizeInPixels.Width;
            int    Height = (int)crt.SizeInPixels.Height;

            WriteableBitmap writeableBitmap = new WriteableBitmap(Width, Height);     //创建新Bitmap,宽高是图片宽高
            Stream          stream          = writeableBitmap.PixelBuffer.AsStream(); //Bitmap=>Stream

            stream.Seek(0, SeekOrigin.Begin);                                         //Stream.Seek寻找(从零开始)
            stream.Write(buffer, 0, buffer.Length);                                   //Stream.Write写入,写入Buffer(从零到其长度)

            return(writeableBitmap);
        }
Exemplo n.º 14
0
 //CanvasDrawingSession ls;
 public override void Invalidate(bool init = false)
 {
     if (init)
     {
         source.SetPixelBytes(b.PixelBuffer);
     }
     else
     {
         session.Dispose();
         source.GetPixelBytes(b.PixelBuffer);
         b.Invalidate();
     }
     session = source.CreateDrawingSession();
     //session.Blend = Blend;
 }
Exemplo n.º 15
0
 public static SoftwareBitmap Resize(SoftwareBitmap softwareBitmap, float newWidth, float newHeight)
 {
     using (var resourceCreator = CanvasDevice.GetSharedDevice())
         using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
             using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, newWidth, newHeight, canvasBitmap.Dpi))
                 using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                     using (var scaleEffect = new ScaleEffect())
                     {
                         scaleEffect.Source = canvasBitmap;
                         scaleEffect.Scale  = new System.Numerics.Vector2(newWidth / softwareBitmap.PixelWidth, newHeight / softwareBitmap.PixelHeight);
                         drawingSession.DrawImage(scaleEffect);
                         drawingSession.Flush();
                         return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied));
                     }
 }
Exemplo n.º 16
0
        private static async Task CropImageWithShapeAsync(WriteableBitmap writeableBitmap, IRandomAccessStream stream, Rect croppedRect, BitmapFileFormat bitmapFileFormat, CropShape cropShape)
        {
            var device       = CanvasDevice.GetSharedDevice();
            var clipGeometry = CreateClipGeometry(device, cropShape, new Size(croppedRect.Width, croppedRect.Height));

            if (clipGeometry == null)
            {
                return;
            }

            CanvasBitmap sourceBitmap = null;

            using (var randomAccessStream = new InMemoryRandomAccessStream())
            {
                await CropImageAsync(writeableBitmap, randomAccessStream, croppedRect, bitmapFileFormat);

                sourceBitmap = await CanvasBitmap.LoadAsync(device, randomAccessStream);
            }

            using (var offScreen = new CanvasRenderTarget(device, (float)croppedRect.Width, (float)croppedRect.Height, 96f))
            {
                using (var drawingSession = offScreen.CreateDrawingSession())
                    using (var markCommandList = new CanvasCommandList(device))
                    {
                        using (var markDrawingSession = markCommandList.CreateDrawingSession())
                        {
                            markDrawingSession.FillGeometry(clipGeometry, Colors.Black);
                        }

                        var alphaMaskEffect = new AlphaMaskEffect
                        {
                            Source    = sourceBitmap,
                            AlphaMask = markCommandList
                        };
                        drawingSession.DrawImage(alphaMaskEffect);
                        alphaMaskEffect.Dispose();
                    }

                clipGeometry.Dispose();
                sourceBitmap.Dispose();
                var pixelBytes    = offScreen.GetPixelBytes();
                var bitmapEncoder = await BitmapEncoder.CreateAsync(GetEncoderId(bitmapFileFormat), stream);

                bitmapEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, offScreen.SizeInPixels.Width, offScreen.SizeInPixels.Height, 96.0, 96.0, pixelBytes);
                await bitmapEncoder.FlushAsync();
            }
        }
        /// <summary>
        /// Save image with Ink
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ButtonSaveImage_ClickAsync(object sender, RoutedEventArgs e)
        {
            // The original bitmap from the screen, missing the ink.
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap();
            await renderBitmap.RenderAsync(this.gridInk);

            Size bitmapSizeAt96Dpi = new Size(renderBitmap.PixelWidth, renderBitmap.PixelHeight);

            IBuffer renderBitmapPixels = await renderBitmap.GetPixelsAsync();

            CanvasDevice win2DDevice = CanvasDevice.GetSharedDevice();

            DisplayInformation displayInfo = DisplayInformation.GetForCurrentView();

            using (CanvasRenderTarget win2DTarget = new CanvasRenderTarget(win2DDevice, (float)this.gridInk.ActualWidth, (float)this.gridInk.ActualHeight, 96.0f))
            {
                using (CanvasDrawingSession win2dSession = win2DTarget.CreateDrawingSession())
                {
                    using (CanvasBitmap win2dRenderedBitmap = CanvasBitmap.CreateFromBytes(win2DDevice, renderBitmapPixels, (int)bitmapSizeAt96Dpi.Width, (int)bitmapSizeAt96Dpi.Height, DirectXPixelFormat.B8G8R8A8UIntNormalized, 96.0f))
                    {
                        win2dSession.DrawImage(win2dRenderedBitmap, new Rect(0, 0, win2DTarget.SizeInPixels.Width, win2DTarget.SizeInPixels.Height), new Rect(0, 0, bitmapSizeAt96Dpi.Width, bitmapSizeAt96Dpi.Height));
                    }
                    win2dSession.Units = CanvasUnits.Pixels;
                    win2dSession.DrawInk(this.inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                //Get file and save
                FileSavePicker picker = new FileSavePicker();
                picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
                StorageFile file = await picker.PickSaveFileAsync();

                if (file != null)
                {
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                             BitmapAlphaMode.Ignore,
                                             (uint)this.gridInk.ActualWidth, (uint)this.gridInk.ActualHeight,
                                             96, 96, win2DTarget.GetPixelBytes());

                        await encoder.FlushAsync();
                    }
                }
            }
        }
        public async Task <StorageFile> SaveDoodle()
        {
            storageFolder = KnownFolders.SavedPictures;
            //var file = await storageFolder.CreateFileAsync("ink.png", CreationCollisionOption.ReplaceExisting);

            if (ink_canvas.InkPresenter.StrokeContainer.GetStrokes().Count == 0)
            {
                finishfile = sourcefile;
            }
            else
            {
                CanvasDevice       device       = CanvasDevice.GetSharedDevice();
                CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)ink_canvas.ActualWidth, (int)ink_canvas.ActualHeight, 96);
                renderTarget.SetPixelBytes(new byte[(int)ink_canvas.ActualWidth * 4 * (int)ink_canvas.ActualHeight]);
                using (var ds = renderTarget.CreateDrawingSession())
                {
                    IReadOnlyList <InkStroke> inklist = ink_canvas.InkPresenter.StrokeContainer.GetStrokes();

                    Debug.WriteLine("Ink_Strokes Count:  " + inklist.Count);
                    //ds.Clear(Colors.White);
                    ds.DrawInk(inklist);
                }

                //直接存的ink
                //using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                //{
                //    await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
                //}

                var inkpixel = renderTarget.GetPixelBytes();
                //var color = renderTarget.GetPixelColors();

                WriteableBitmap bmp = new WriteableBitmap((int)ink_canvas.ActualWidth, (int)ink_canvas.ActualHeight);
                Stream          s   = bmp.PixelBuffer.AsStream();
                s.Seek(0, SeekOrigin.Begin);
                s.Write(inkpixel, 0, (int)ink_canvas.ActualWidth * 4 * (int)ink_canvas.ActualHeight);

                WriteableBitmap ink_wb = await ImageProcessing.ResizeByDecoderAsync(bmp, sourceImage.PixelWidth, sourceImage.PixelHeight, true);

                //await SaveToFile("ink_scale.png", ink_wb);
                WriteableBitmap combine_wb = await ImageProcessing.CombineAsync(sourceImage, ink_wb);

                finishfile = await WriteableBitmapSaveToFile(combine_wb);
            }
            Clear();
            return(finishfile);
        }
        public static void CalculateGradient(
            Color clr1,
            Color clr2,
            int nThickness,
            IList <Color> list)
        {
            list.Clear();
            int nWidth = nThickness;

            CanvasGradientStop[] grad_stops = new CanvasGradientStop[2];
            grad_stops[0]          = new CanvasGradientStop();
            grad_stops[0].Color    = clr1;
            grad_stops[0].Position = 0.0f;
            grad_stops[1]          = new CanvasGradientStop();
            grad_stops[1].Color    = clr2;
            grad_stops[1].Position = 1.0f;
            CanvasDevice device             = CanvasDevice.GetSharedDevice();
            CanvasLinearGradientBrush brush = new CanvasLinearGradientBrush(device, grad_stops);

            brush.StartPoint = new Vector2(0, 0);
            brush.EndPoint   = new Vector2(nWidth, 0);

            using (CanvasRenderTarget offscreen = new CanvasRenderTarget(device, nWidth, 1, 96, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                                         CanvasAlphaMode.Premultiplied))
            {
                using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
                {
                    ds.DrawRectangle(new Rect(0, 0, nWidth, 1), brush);
                }

                uint   stride = 4;
                byte[] pixels = offscreen.GetPixelBytes();

                for (uint row = 0; row < 1; ++row)
                {
                    for (uint col = 0; col < nWidth; ++col)
                    {
                        uint  index    = (uint)(row * stride + col) * 4;
                        uint  color    = pixels[index];
                        Color gdiColor = Color.FromArgb(pixels[index + 3], pixels[index + 2], pixels[index + 1], pixels[index]);
                        list.Add(gdiColor);
                    }
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Helper metohd that crop a SoftwareBitmap given a new bounding box
 /// </summary>
 private SoftwareBitmap CropSoftwareBitmap(SoftwareBitmap softwareBitmap, float x, float y, float width, float height)
 {
     using (var resourceCreator = CanvasDevice.GetSharedDevice())
         using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
             using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, width, height, canvasBitmap.Dpi))
                 using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                     using (var cropEffect = new CropEffect())
                     {
                         cropEffect.Source = canvasBitmap;
                         drawingSession.DrawImage(
                             cropEffect,
                             new Rect(0.0, 0.0, width, height),
                             new Rect(x, y, width, height),
                             (float)1.0,
                             CanvasImageInterpolation.HighQualityCubic);
                         drawingSession.Flush();
                         return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Rgba8, (int)width, (int)height, BitmapAlphaMode.Premultiplied));
                     }
 }
Exemplo n.º 21
0
        private void ThumbnailButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            CanvasRenderTarget Thumbnail = new CanvasRenderTarget(App.Model.VirtualControl, ThumbnailWidth, ThumbnailHeight);

            using (var ds = Thumbnail.CreateDrawingSession())
            {
                var space = App.Setting.PaintSpace * (float)Math.Sqrt(App.Setting.PaintWidth);
                for (float x = 10; x < ThumbnailWidth - 10; x += space)
                {
                    //根据画布的X位置,求Sin高度角度(一条上下弧线)
                    var   sinh = x / ThumbnailWidth * Math.PI * 2;
                    float h    = 20 * (float)Math.Sin(sinh);//上下浮动

                    //根据画布的X位置,求Sin大小角度(一个上凸曲线)
                    var         sins = x / ThumbnailWidth * Math.PI;
                    Vector2     s    = new Vector2((float)Math.Sin(sins));//大小浮动
                    ScaleEffect se   = new ScaleEffect {
                        Source = App.Setting.PaintShow, Scale = s
                    };

                    ds.DrawImage(se, x, (float)ThumbnailHeight / 2 + h);
                }
            }

            string ss = "-" + (App.Setting.PaintWidth).ToString() + "-" + (App.Setting.PaintHard).ToString() + "-" + (App.Setting.PaintOpacity).ToString() + "-" + (App.Setting.PaintSpace).ToString();

            byte[] bytes = Thumbnail.GetPixelBytes();
            修图.Library.Image.SavePng(KnownFolders.SavedPictures, bytes, ThumbnailWidth, ThumbnailHeight, ss);

            string path = "Icon/Clutter/OK.png";

            修图.Library.Toast.ShowToastNotification(path, "已保存到本地相册");



            App.Tip(ss);//全局提示

            DataPackage dataPackage = new DataPackage();

            dataPackage.SetText(ss);
            Clipboard.SetContent(dataPackage);
        }
Exemplo n.º 22
0
        private async void SaveFile(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var canvas = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(),
                                                (float)AnimatedCanvas.Size.Width,
                                                (float)AnimatedCanvas.Size.Height,
                                                96);

            using (var canvasDS = canvas.CreateDrawingSession())
            {
                DrawLocal(canvasDS, AnimatedCanvas.Size);
                DrawBitmap1(canvasDS, AnimatedCanvas.Size);
                DrawBitmap2(canvasDS, AnimatedCanvas.Size);
                DrawLines(canvasDS, AnimatedCanvas.Size);
            }

            var picker = new FileSavePicker();

            picker.FileTypeChoices.Add("image", new List <string> {
                ".png"
            });
            var file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var bytes = canvas.GetPixelBytes();

                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                         BitmapAlphaMode.Straight,
                                         canvas.SizeInPixels.Width,
                                         canvas.SizeInPixels.Height,
                                         96,
                                         96,
                                         bytes);

                    await encoder.FlushAsync();
                }
            }
        }
Exemplo n.º 23
0
        private static CanvasBitmap getGraphic(Color color)
        {
            if (Graphics.ContainsKey(color))
            {
                return(Graphics[color]);
            }

            var g2 = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (int)Graphics[Colors.White].Size.Width, (int)Graphics[Colors.White].Size.Height, DPI);

            g2.CopyPixelsFromBitmap(Graphics[Colors.White]);
            var arr = g2.GetPixelBytes();

            for (int i = 0; i < arr.Length; i += 4)
            {
                arr[i]     = (byte)(((float)arr[i] / 255) * ((float)color.B / 255) * 255);
                arr[i + 1] = (byte)(((float)arr[i + 1] / 255) * ((float)color.G / 255) * 255);
                arr[i + 2] = (byte)(((float)arr[i + 2] / 255) * ((float)color.R / 255) * 255);
            }
            g2.SetPixelBytes(arr);
            Graphics[color] = g2;
            return(g2);
        }
Exemplo n.º 24
0
        public async Task <StorageFile> DrawAsync()
        {
            if (!CheckResources())
            {
                throw new ArgumentOutOfRangeException();
            }

            var size      = GetTileSize();
            var device    = CanvasDevice.GetSharedDevice();
            var offscreen = new CanvasRenderTarget(device, (float)size.Width, (float)size.Height, 96);

            using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);
                for (int i = 0; i < List.Count(); i++)
                {
                    var todo = List[i];
                    ds.DrawTextLayout(CreateTextLayout(device, todo.Content), new Vector2(10f, 10 * i),
                                      new CanvasSolidColorBrush(device, Colors.White));
                }
            }

            var cacheFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("LiveTile", CreationCollisionOption.OpenIfExists);

            var file = await cacheFolder.CreateFileAsync($"{TileKind.ToString()}.png", CreationCollisionOption.GenerateUniqueName);

            var bytes = offscreen.GetPixelBytes();

            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fs);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)size.Width, (uint)size.Height, 96, 96, bytes);
                await encoder.FlushAsync();
            }

            return(file);
        }
Exemplo n.º 25
0
        public void Resize(ref ImageCanvasDataService imageHolst)
        {
            int width          = imageHolst.Width;
            int height         = imageHolst.Height;
            var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8,
                                                    imageHolst.Image.PixelWidth,
                                                    imageHolst.Image.PixelHeight);

            imageHolst.Image.CopyTo(softwareBitmap);
            byte[] imageBytes = new byte[softwareBitmap.PixelHeight * softwareBitmap.PixelWidth * 4];
            softwareBitmap.CopyToBuffer(imageBytes.AsBuffer());
            var resourceCreator = CanvasDevice.GetSharedDevice();
            var canvasBitmap    = CanvasBitmap.CreateFromBytes(
                resourceCreator,
                imageBytes,
                softwareBitmap.PixelWidth,
                softwareBitmap.PixelHeight,
                Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                96.0f);

            var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, width, height, 96);

            using (var cds = canvasRenderTarget.CreateDrawingSession())
            {
                cds.DrawImage(canvasBitmap, canvasRenderTarget.Bounds);
            }

            var pixelBytes = canvasRenderTarget.GetPixelBytes();

            imageHolst.ImageSRC.DecodePixelHeight = height;
            imageHolst.ImageSRC.DecodePixelWidth  = width;

            var scaledSoftwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, width, height);

            scaledSoftwareBitmap.CopyFromBuffer(pixelBytes.AsBuffer());
            imageHolst.Image = scaledSoftwareBitmap;
        }
Exemplo n.º 26
0
        private byte[] ConvertInkCanvasToByteArray(InkCanvas canvas)
        {
            var canvasStrokes = canvas.InkPresenter.StrokeContainer.GetStrokes();

            if (canvasStrokes.Count > 0)
            {
                var width        = (int)canvas.ActualWidth;
                var height       = (int)canvas.ActualHeight;
                var device       = CanvasDevice.GetSharedDevice();
                var renderTarget = new CanvasRenderTarget(device, width, height, 96);

                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(Windows.UI.Colors.White);
                    ds.DrawInk(canvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                return(renderTarget.GetPixelBytes());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 27
0
        public static CanvasRenderTarget GenImage(int width, int height, CanvasLinearGradientBrush brush, byte alpha)
        {
            CanvasDevice device = CanvasDevice.GetSharedDevice();

            CanvasRenderTarget offscreen = new CanvasRenderTarget(device, width, height, 96, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                                  CanvasAlphaMode.Premultiplied);

            using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
            {
                ds.FillRectangle(new Rect(0.0, 0.0, offscreen.SizeInPixels.Width, offscreen.SizeInPixels.Height), brush);
            }

            byte[] pixels = offscreen.GetPixelBytes();

            if (pixels == null)
            {
                return(null);
            }

            uint col    = 0;
            uint stride = offscreen.SizeInPixels.Width;

            for (uint row = 0; row < offscreen.SizeInPixels.Height; ++row)
            {
                uint total_row_len = (uint)(row * stride);
                for (col = 0; col < offscreen.SizeInPixels.Width; ++col)
                {
                    uint index = (total_row_len + col) * 4;

                    pixels[index + 3] = alpha;
                }
            }
            offscreen.SetPixelBytes(pixels);

            return(offscreen);
        }
Exemplo n.º 28
0
        async public Task <RandomAccessStreamReference> GetImage()
        {
            // 1. Příprava
            CanvasDevice device = CanvasDevice.GetSharedDevice();

            // 2. Získáme pozadí jako bitmapu
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(sourceGrid, (int)sourceGrid.ActualWidth, (int)sourceGrid.ActualHeight);

            // 3. Zafixujeme rozměry bitmapy v pixelech
            var bitmapSizeAt96Dpi = new Size(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);

            // 4. Získáme pixely
            IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

            byte[] pixels = pixelBuffer.ToArray();

            // 5. Začneme renderovat při 96 DPI
            using (CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)sourceGrid.ActualWidth, (int)sourceGrid.ActualHeight, 96.0f))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    using (var win2dRenderedBitmap = CanvasBitmap.CreateFromBytes(device, pixels,
                                                                                  (int)bitmapSizeAt96Dpi.Width, (int)bitmapSizeAt96Dpi.Height,
                                                                                  Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                                                  96.0f))
                    {
                        drawingSession.DrawImage(win2dRenderedBitmap,
                                                 new Rect(0, 0, renderTarget.SizeInPixels.Width, renderTarget.SizeInPixels.Height),
                                                 new Rect(0, 0, bitmapSizeAt96Dpi.Width, bitmapSizeAt96Dpi.Height));
                    }

                    // 6. Přidáme ink
                    drawingSession.Units = CanvasUnits.Pixels;
                    drawingSession.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                var outputBitmap = new SoftwareBitmap(
                    BitmapPixelFormat.Bgra8,
                    (int)renderTarget.SizeInPixels.Width,
                    (int)renderTarget.SizeInPixels.Height,
                    BitmapAlphaMode.Premultiplied);

                outputBitmap.CopyFromBuffer(renderTarget.GetPixelBytes().AsBuffer());

                // 7. Vykreslíme do bufferu
                var stream  = new InMemoryRandomAccessStream();
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
                                     (uint)renderTarget.SizeInPixels.Width, (uint)renderTarget.SizeInPixels.Height,
                                     96.0f, 96.0f,
                                     renderTarget.GetPixelBytes()
                                     );
                await encoder.FlushAsync();

                stream.Seek(0);

                return(RandomAccessStreamReference.CreateFromStream(stream));
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Captures the ink from an <see cref="InkCanvas"/> control.
        /// </summary>
        /// <param name="strokeContainer">
        /// The <see cref="InkStrokeContainer"/> containing the strokes to be rendered.
        /// </param>
        /// <param name="rootRenderElement">
        /// A <see cref="FrameworkElement"/> which wraps the canvas.
        /// </param>
        /// <param name="targetFile">
        /// A <see cref="StorageFile"/> to store the image in.
        /// </param>
        /// <param name="encoderId">
        /// A <see cref="BitmapEncoder"/> ID to use to render the image.
        /// </param>
        /// <returns>
        /// Returns the <see cref="StorageFile"/> containing the rendered ink.
        /// </returns>
        public static async Task <StorageFile> CaptureInkToFileAsync(
            this InkStrokeContainer strokeContainer,
            FrameworkElement rootRenderElement,
            StorageFile targetFile,
            Guid encoderId)
        {
            if (targetFile != null)
            {
                var renderBitmap = new RenderTargetBitmap();
                await renderBitmap.RenderAsync(rootRenderElement);

                var bitmapSizeAt96Dpi = new Size(renderBitmap.PixelWidth, renderBitmap.PixelHeight);

                var pixels = await renderBitmap.GetPixelsAsync();

                var win2DDevice = CanvasDevice.GetSharedDevice();

                using (
                    var target = new CanvasRenderTarget(
                        win2DDevice,
                        (float)rootRenderElement.ActualWidth,
                        (float)rootRenderElement.ActualHeight,
                        96.0f))
                {
                    using (var drawingSession = target.CreateDrawingSession())
                    {
                        using (
                            var canvasBitmap = CanvasBitmap.CreateFromBytes(
                                win2DDevice,
                                pixels,
                                (int)bitmapSizeAt96Dpi.Width,
                                (int)bitmapSizeAt96Dpi.Height,
                                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                96.0f))
                        {
                            drawingSession.DrawImage(
                                canvasBitmap,
                                new Rect(0, 0, target.SizeInPixels.Width, target.SizeInPixels.Height),
                                new Rect(0, 0, bitmapSizeAt96Dpi.Width, bitmapSizeAt96Dpi.Height));
                        }
                        drawingSession.Units = CanvasUnits.Pixels;
                        drawingSession.DrawInk(strokeContainer.GetStrokes());
                    }

                    using (var stream = await targetFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        var displayInfo = DisplayInformation.GetForCurrentView();
                        var encoder     = await BitmapEncoder.CreateAsync(encoderId, stream);

                        encoder.SetPixelData(
                            BitmapPixelFormat.Bgra8,
                            BitmapAlphaMode.Ignore,
                            target.SizeInPixels.Width,
                            target.SizeInPixels.Height,
                            displayInfo.RawDpiX,
                            displayInfo.RawDpiY,
                            target.GetPixelBytes());

                        await encoder.FlushAsync();
                    }
                }
            }

            return(targetFile);
        }
Exemplo n.º 30
0
        private void DryWaitingStroke([NotNull] TileCanvas tileCanvas)
        {
            // Try to get a waiting stroke (peek, so we can draw the waiting stroke)
            DPoint[][] waitingStrokes;
            lock (_dryLock)
            {
                waitingStrokes = _dryingInk.ToArray();
                _dryingInk.Clear();
                if (waitingStrokes != null)
                {
                    _renderingInk.UnionWith(waitingStrokes);
                }
            }

            tileCanvas.Invalidate(); // show progress if the render is slow.
            _renderTarget.Invalidate();

            if (waitingStrokes == null)
            {
                return;
            }
            foreach (var strokeToRender in waitingStrokes)
            {
                if (strokeToRender.Length < 1)
                {
                    continue;
                }

                // Figure out what part of the screen is covered
                var clipRegion  = MeasureDrawing(strokeToRender, tileCanvas.CurrentZoom());
                var pixelWidth  = (int)clipRegion.Width;
                var pixelHeight = (int)clipRegion.Height;

                // draw to an image
                byte[] bytes;
                using (var offscreen = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), pixelWidth, pixelHeight, 96,
                                                              DirectXPixelFormat.B8G8R8A8UIntNormalized, CanvasAlphaMode.Premultiplied))
                {
                    using (var ds = offscreen.CreateDrawingSession())
                    {
                        ds?.Clear(Colors.Transparent);
                        DrawToSession(ds, strokeToRender, clipRegion, tileCanvas.CurrentZoom());
                    }

                    bytes = offscreen.GetPixelBytes();
                }

                // render into tile cache
                var uncropped = new RawImageInterleaved_UInt8
                {
                    Data   = bytes,
                    Width  = pixelWidth,
                    Height = pixelHeight
                };

                var visualWidth  = (int)Math.Ceiling(pixelWidth / tileCanvas.CurrentZoom());
                var visualHeight = (int)Math.Ceiling(pixelHeight / tileCanvas.CurrentZoom());
                var visualTop    = (int)Math.Floor(clipRegion.Y + 0.5);
                var visualLeft   = (int)Math.Floor(clipRegion.X + 0.5);
                var visualRight  = visualLeft + visualWidth;
                var visualBottom = visualTop + visualHeight;

                ThreadPool.QueueUserWorkItem(canv =>
                {
                    var ok = tileCanvas.ImportBytesScaled(uncropped, visualLeft, visualTop, visualRight, visualBottom);
                    if (!ok)
                    {
                        Logging.WriteLogMessage("Tile byte import failed when drawing strokes");
                    }
                    lock (_dryLock)
                    {
                        _renderingInk.Remove(strokeToRender);
                    }
                    tileCanvas.Invalidate(); // show finished strokes
                    _renderTarget.Invalidate();
                });
            }
        }
Exemplo n.º 31
0
        public async void DrawEffect()
        {
            if (Target == null)
            {
                return;
            }

            if (MainContainer != null)
            {
                foreach (var child in MainContainer.Children)
                {
                    if (child is SpriteVisual)
                    {
                        (child as SpriteVisual).Brush.Dispose();
                    }
                }
                RemoveEffect();
            }

            RenderTargetBitmap bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(Target);
            var pixels  = (await bitmap.GetPixelsAsync()).ToArray();
            
            Size srcSize = new Size(bitmap.PixelWidth, bitmap.PixelHeight);
            Size decSize = new Size((int)BlurAmount * 10 + bitmap.PixelWidth, (int)BlurAmount * 10 + bitmap.PixelHeight);
            Size blurSize = new Size(decSize.Width - srcSize.Width, decSize.Height - srcSize.Height);
            Point transform = new Point(blurSize.Width/2, blurSize.Height/2);
            transform.X += Math.Cos(Direction / 360 * 2 * Math.PI) * Depth;
            transform.Y += Math.Sin(Direction / 360 * 2 * Math.PI) * Depth;
            
            ContainerVisual visual = Target.GetVisual() as ContainerVisual;

            Compositor compositor = visual.Compositor;

            CanvasDevice device = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget offscreen = new CanvasRenderTarget(device, (int)decSize.Width, (int)decSize.Height, 96);

            using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
            {
                Transform2DEffect finalEffect = new Transform2DEffect()
                {
                    Source = new Microsoft.Graphics.Canvas.Effects.ShadowEffect()
                    {
                        Source = CanvasBitmap.CreateFromBytes(ds, pixels, (int)srcSize.Width, (int)srcSize.Height,
                                DirectXPixelFormat.B8G8R8A8UIntNormalized),
                        BlurAmount = (float)BlurAmount,
                        ShadowColor = ShadowColor
                    },
                    TransformMatrix = Matrix3x2.CreateTranslation((float)blurSize.Width / 2, (float)blurSize.Height / 2)
                };


                ds.DrawImage(finalEffect);
            }

            var effectPixels = offscreen.GetPixelBytes();

            var imageFactory =
                Microsoft.UI.Composition.Toolkit.CompositionImageFactory.CreateCompositionImageFactory(compositor);

            var effectImage = imageFactory.CreateImageFromPixels(effectPixels, (int)decSize.Width, (int)decSize.Height);
            var effectbrush = compositor.CreateSurfaceBrush(effectImage.Surface);
            var effectVisual = compositor.CreateSpriteVisual();

            effectVisual.Brush = effectbrush;
            effectVisual.Offset = new Vector3( -(float)transform.X, -(float)transform.Y, 0);
            effectVisual.Size = new Vector2((float)decSize.Width, (float)decSize.Height);

            var srcImage = imageFactory.CreateImageFromPixels(pixels, (int)srcSize.Width, (int)srcSize.Height);
            var srcbrush = compositor.CreateSurfaceBrush(srcImage.Surface);
            var srcVisual = compositor.CreateSpriteVisual();

            srcVisual.Brush = srcbrush;
            srcVisual.Offset = new Vector3(0, 0, 0);
            srcVisual.Size = new Vector2((int)srcSize.Width, (int)srcSize.Height);

            if (MainContainer == null)
            {
                MainContainer = compositor.CreateContainerVisual();
                ElementCompositionPreview.SetElementChildVisual(Target, MainContainer);
            }

            MainContainer.Children.InsertAtTop(srcVisual);
            MainContainer.Children.InsertAtBottom(effectVisual);
        }