예제 #1
0
        void TestSaveAsync(Func <CanvasDevice, ICanvasImage> createImage)
        {
            const int width  = 23;
            const int height = 42;

            var device      = new CanvasDevice();
            var sourceImage = createImage(device);
            var stream      = new MemoryStream();

            var saveTask = Task.Run(async() =>
            {
                await CanvasImage.SaveAsync(sourceImage, new Rect(0, 0, width, height), 96, device, stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png);
            });

            saveTask.Wait();

            CanvasBitmap result = null;

            var loadTask = Task.Run(async() =>
            {
                result = await CanvasBitmap.LoadAsync(device, stream.AsRandomAccessStream());
            });

            loadTask.Wait();

            Assert.AreEqual(width, result.Size.Width);
            Assert.AreEqual(height, result.Size.Height);
        }
예제 #2
0
        public override void Run(IAnsiConsole console)
        {
            var image = new CanvasImage("../../../examples/Console/Canvas/cake.png");

            image.MaxWidth(16);
            console.Write(image);
        }
예제 #3
0
        public static void Main()
        {
            // Draw a mandelbrot set using a Canvas
            var mandelbrot = Mandelbrot.Generate(32, 32);

            Render(mandelbrot, "Mandelbrot");

            // Draw an image using CanvasImage powered by ImageSharp.
            // This requires the "Spectre.Console.ImageSharp" NuGet package.
            var image = new CanvasImage("cake.png");

            image.BilinearResampler();
            image.MaxWidth(16);
            Render(image, "Image from file (16 wide)");

            // Draw image again, but without render width
            image.NoMaxWidth();
            image.Mutate(ctx => ctx.Grayscale().Rotate(-45).EntropyCrop());
            Render(image, "Image from file (fit, greyscale, rotated)");

            // Draw image again, but load from embedded resource rather than file
            using (var fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Canvas.cake.png"))
            {
                Debug.Assert(fileStream != null);
                var embeddedImage = new CanvasImage(fileStream);
                embeddedImage.BilinearResampler();
                embeddedImage.MaxWidth(16);
                Render(embeddedImage, "Image from embedded resource (16 wide)");
            }
        }
예제 #4
0
        public Canvas CreateCanvas(String name)
        {
            if (databaseContext.Canvases.Find(name) != null)
            {
                BadRequest("A canvas with this name already exists");
            }

            Canvas newCanvas = new Canvas();

            newCanvas.Name    = name;
            newCanvas.Version = 1;
            databaseContext.Canvases.Add(newCanvas);
            databaseContext.SaveChanges();

            CanvasImage canvasImage = new CanvasImage();

            canvasImage.InitializeBitmap();
            canvasImage.canvas = databaseContext.Canvases.Find(name);
            canvasImage.Name   = name;
            databaseContext.CanvasImages.Add(canvasImage);

            databaseContext.SaveChanges();

            return(newCanvas);
        }
예제 #5
0
        //创建直方图
        private void DrawHistogram(CanvasDrawingSession drawingSession, Size size, EffectChannelSelect channelSelect, CanvasLinearGradientBrush brush)
        {
            int         binCount   = (int)CanvasControl.ActualWidth; //256;//矩形数量
            const float graphPower = 0.25f;                          // 非线性规模使得图更清楚地显示微小的变化。

            try
            {
                float[] histogram = CanvasImage.ComputeHistogram(App.Model.MainRenderTarget, App.Model.MainRenderTarget.Bounds, drawingSession, channelSelect, binCount);

                var w = (float)size.Width / binCount;
                var h = (float)size.Height;

                for (int i = 0; i < binCount; i++)
                {
                    var x = i * w;
                    var y = (1 - (float)Math.Pow(histogram[i], graphPower)) * h;

                    brush.StartPoint = new Vector2(x, y);
                    brush.EndPoint   = new Vector2(x, h);

                    drawingSession.FillRectangle(x, y, w, h - y, brush);
                }
            }
            catch (Exception)  {  }
        }
예제 #6
0
        public void DeleteCanvas(String name)
        {
            Canvas canvas = databaseContext.Canvases.Find(name);

            if (canvas == null)
            {
                NotFound();
            }
            databaseContext.Canvases.Remove(canvas);

            CanvasImage canvasImage = databaseContext.CanvasImages.Find(name);

            if (canvasImage != null)
            {
                databaseContext.CanvasImages.Remove(canvasImage);
            }


            List <PixelChange> pixelChanges = databaseContext.PixelChanges.Where(p => p.Canvas.Name == canvas.Name).ToList();

            foreach (PixelChange pixelChange in pixelChanges)
            {
                databaseContext.PixelChanges.Remove(pixelChange);
            }

            databaseContext.SaveChanges();
        }
예제 #7
0
        /// GET: CanvasImage?name=""&version=#
        /// Returns a .png image representing the canvas.
        ///
        public ActionResult Index(String name, String version)
        {
            // Check for cached image first
            System.IO.MemoryStream cachedMemoryStream = (System.IO.MemoryStream)System.Web.HttpContext.Current.Cache.Get(name + "&" + version);
            if (cachedMemoryStream != null)
            {
                return(File(cachedMemoryStream.ToArray(), "image/png"));
            }

            // Get canvas from database
            CanvasImage canvasImage = databaseContext.CanvasImages.Find(name);

            if (canvasImage == null)
            {
                return(HttpNotFound());
            }

            // Apply all changed pixels, save, and generate png
            ApplyChangedPixelsToImage(canvasImage);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            canvasImage.GetBitmap().Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            // Save to cache
            System.Web.HttpContext.Current.Cache.Insert(name + "&" + version, (object)ms);

            return(File(ms.ToArray(), "image/png"));
        }
예제 #8
0
        /// <summary>
        /// Helper method that applies any pixel changes between the image version and the latest version
        /// </summary>
        /// <param name="canvas">Which canvas to apply changes to</param>
        private void ApplyChangedPixelsToImage(CanvasImage canvasImage)
        {
            Canvas canvas = canvasImage.canvas;

            // Get changed pixels
            IEnumerable <PixelChange> pixelChanges = databaseContext.PixelChanges
                                                     .Where(p => p.CanvasVersion > canvas.ImageVersion && p.Canvas.Name == canvas.Name)
                                                     .OrderBy(p => p.CanvasVersion);

            if (!pixelChanges.Any())
            {
                return;
            }

            // Update bitmap with changes
            Bitmap bitmap = canvasImage.GetBitmap();

            foreach (PixelChange pixelChange in pixelChanges)
            {
                bitmap.SetPixel(pixelChange.X, pixelChange.Y, ColorTranslator.FromHtml(pixelChange.Color));
                //placeContext.PixelChanges.Remove(pixelChange);
            }

            canvasImage.SetBitmap(bitmap);

            canvas.ImageVersion = pixelChanges.Last().CanvasVersion;
            databaseContext.SaveChanges();
        }
        private void CanvasPanel_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                var x = Mouse.GetPosition(CanvasPanel).X;
                var y = Mouse.GetPosition(CanvasPanel).Y;

                if (x >= _ellipseHalfWidth && x <= CanvasImage.Width - _ellipseHalfWidth - 1 && y >= _ellipseHalfHeight && y <= CanvasImage.Height - _ellipseHalfHeight - 1)
                {
                    try
                    {
                        var croppedBitmap = new CroppedBitmap(ColorImage.Source as BitmapSource, new Int32Rect(Convert.ToInt32(x), Convert.ToInt32(y), 1, 1));
                        var pixels        = new byte[4];
                        croppedBitmap.CopyPixels(pixels, 4, 0);
                        SelectedColor = Color.FromArgb(255, pixels[2], pixels[1], pixels[0]);
                        MoveEllipse(x, y, SelectedColor);
                        UpdateTextBox();
                        ColorRectangle.Fill = new SolidColorBrush(SelectedColor);
                    }
                    catch (Exception)
                    {
                        _isMouseDown = false;
                        SetColor(Colors.White);
                    }
                    finally
                    {
                        CanvasImage.InvalidateVisual();
                    }
                }
                else
                {
                    _isMouseDown = false;
                }
            }
        }
예제 #10
0
        public override IView ConvertToView(FigmaNode currentNode, ViewNode parent, ViewRenderService rendererService)
        {
            var currengroupView = new CanvasImage();

            currengroupView.Configure((FigmaRegularPolygon)currentNode);
            return(new ImageView());// currengroupView);
        }
예제 #11
0
        public override IViewWrapper ConvertTo(FigmaNode currentNode, ProcessedNode parent)
        {
            var currengroupView = new CanvasImage();

            currengroupView.Configure((FigmaRegularPolygon)currentNode);
            return(new ImageViewWrapper(currengroupView));
        }
예제 #12
0
        private async void DialController_ButtonClicked(RadialController sender, RadialControllerButtonClickedEventArgs args)
        {
            try
            {
                ShowBusyIndicator("saving file...");

                var picker = new FileSavePicker();
                picker.FileTypeChoices.Add("Jpegs", new List <string>()
                {
                    ".jpg"
                });

                var file = await picker.PickSaveFileAsync();

                if (file == null)
                {
                    return;
                }

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // watermark the image
                    var device = CanvasDevice.GetSharedDevice();

                    var bounds = virtualBitmap.Bounds;

                    var text = new CanvasCommandList(device);
                    using (var ds = text.CreateDrawingSession())
                    {
                        ds.DrawText("Created by Dial-In", bounds, Colors.White,
                                    new CanvasTextFormat
                        {
                            VerticalAlignment   = CanvasVerticalAlignment.Bottom,
                            HorizontalAlignment = CanvasHorizontalAlignment.Right,
                            FontFamily          = "Segoe UI",
                            FontSize            = (float)(bounds.Height / 12)
                        });
                    }

                    var effect = new BlendEffect()
                    {
                        Background = virtualBitmap,
                        Foreground = text,
                        Mode       = BlendEffectMode.Difference
                    };

                    // save the image to final file
                    await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog($"Something went wrong saving the image: {ex}", "Exception").ShowAsync();
            }
            finally
            {
                HideBusyIndicator();
            }
        }
예제 #13
0
        public void CanvasImage_SaveAsync_HdrFormats()
        {
            var pixelFormats = new Dictionary <CanvasBufferPrecision, DirectXPixelFormat>
            {
                { CanvasBufferPrecision.Precision8UIntNormalized, DirectXPixelFormat.B8G8R8A8UIntNormalized },
                { CanvasBufferPrecision.Precision16Float, DirectXPixelFormat.R16G16B16A16Float },
                { CanvasBufferPrecision.Precision32Float, DirectXPixelFormat.R32G32B32A32Float },
                { CanvasBufferPrecision.Precision16UIntNormalized, DirectXPixelFormat.R16G16B16A16UIntNormalized },
            };

            CanvasBitmapFileFormat[] fileFormats =
            {
                CanvasBitmapFileFormat.Bmp,
                CanvasBitmapFileFormat.Gif,
                CanvasBitmapFileFormat.Jpeg,
                CanvasBitmapFileFormat.JpegXR,
                CanvasBitmapFileFormat.Png,
                CanvasBitmapFileFormat.Tiff,
            };

            var device       = new CanvasDevice();
            var sourceBitmap = new CanvasRenderTarget(device, 1, 1, 96);

            foreach (var pixelFormat in pixelFormats)
            {
                foreach (var fileFormat in fileFormats)
                {
                    bool fileFormatSupportsHdr = (fileFormat == CanvasBitmapFileFormat.JpegXR);

                    using (var stream = new MemoryStream())
                    {
                        var saveTask = CanvasImage.SaveAsync(sourceBitmap,
                                                             sourceBitmap.Bounds,
                                                             sourceBitmap.Dpi,
                                                             device,
                                                             stream.AsRandomAccessStream(),
                                                             fileFormat,
                                                             0.9f,
                                                             pixelFormat.Key).AsTask();
                        saveTask.Wait();

                        var loadTask = CanvasBitmap.LoadAsync(device, stream.AsRandomAccessStream()).AsTask();
                        loadTask.Wait();

                        var loadedBitmap = loadTask.Result;

                        var expectedFormat = pixelFormat.Value;

                        if (!fileFormatSupportsHdr || !device.IsPixelFormatSupported(expectedFormat))
                        {
                            expectedFormat = DirectXPixelFormat.B8G8R8A8UIntNormalized;
                        }

                        Assert.AreEqual(expectedFormat, loadedBitmap.Format, "File format: {0}, pixel format: {1}", fileFormat, pixelFormat);
                    }
                }
            }
        }
예제 #14
0
        public override void Run(IAnsiConsole console)
        {
            var image = new CanvasImage("../../../examples/Console/Canvas/cake.png");

            image.MaxWidth(24);
            image.BilinearResampler();
            image.Mutate(ctx => ctx.Grayscale().Rotate(-45).EntropyCrop());
            console.Write(image);
        }
예제 #15
0
        public override IView ConvertToView(FigmaNode currentNode, ViewNode parent, ViewRenderService rendererService)
        {
            var figmaEntity = (FigmaVector)currentNode;

            var image          = new CanvasImage();
            var figmaImageView = new ImageView();

            image.Configure(figmaEntity);
            return(figmaImageView);
        }
예제 #16
0
    /// <summary>
    /// Sets the pixel width.
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <param name="width">The pixel width.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage PixelWidth(this CanvasImage image, int width)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        image.PixelWidth = width;
        return(image);
    }
예제 #17
0
    /// <summary>
    /// Disables the maximum width of the rendered image.
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage NoMaxWidth(this CanvasImage image)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        image.MaxWidth = null;
        return(image);
    }
예제 #18
0
    /// <summary>
    /// Uses a bilinear sampler. This interpolation algorithm
    /// can be used where perfect image transformation with pixel matching is impossible,
    /// so that one can calculate and assign appropriate intensity values to pixels.
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage BilinearResampler(this CanvasImage image)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        image.Resampler = KnownResamplers.Triangle;
        return(image);
    }
예제 #19
0
    /// <summary>
    /// Uses a bicubic sampler that implements the bicubic kernel algorithm W(x).
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage BicubicResampler(this CanvasImage image)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        image.Resampler = KnownResamplers.Bicubic;
        return(image);
    }
예제 #20
0
        public override IViewWrapper ConvertTo(FigmaNode currentNode, ProcessedNode parent)
        {
            var vector = ((FigmaRectangleVector)currentNode);

            var image          = new CanvasImage();
            var figmaImageView = new ImageViewWrapper();

            image.Configure(vector);
            return(figmaImageView);
        }
예제 #21
0
        public override IViewWrapper ConvertTo(FigmaNode currentNode, ProcessedNode parent)
        {
            var figmaEntity = (FigmaVectorEntity)currentNode;

            var image          = new CanvasImage();
            var figmaImageView = new ImageViewWrapper();

            image.Configure(figmaEntity);
            return(figmaImageView);
        }
예제 #22
0
    /// <summary>
    /// Uses a Nearest-Neighbour sampler that implements the nearest neighbor algorithm.
    /// This uses a very fast, unscaled filter which will select the closest pixel to
    /// the new pixels position.
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage NearestNeighborResampler(this CanvasImage image)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        image.Resampler = KnownResamplers.NearestNeighbor;
        return(image);
    }
        public override IView ConvertTo(FigmaNode currentNode, ProcessedNode parent, FigmaRendererService rendererService)
        {
            var vector = (RectangleVector)currentNode;

            var image          = new CanvasImage();
            var figmaImageView = new ImageView();

            image.Configure(vector);
            return(figmaImageView);
        }
예제 #24
0
        /// <summary>
        /// Update the read state of this item from the message.
        /// </summary>
        public void UpdateImage()
        {
            CanvasImage imageItem = (CanvasImage)CanvasItemLayout[ActionID.AuthorImage];

            if (imageItem != null)
            {
                imageItem.Image = Image;
                Invalidate();
            }
        }
예제 #25
0
        public override IView ConvertTo(FigmaNode currentNode, ProcessedNode parent, FigmaRendererService rendererService)
        {
            var figmaEntity = (FigmaElipse)currentNode;

            var image      = new CanvasImage();
            var elipseView = new View(image);

            image.Configure(figmaEntity);

            return(elipseView);
        }
        public static iText.Layout.Element.Image ToIText(this CanvasImage canvasImage)
        {
            var info = new UIElementInfo(canvasImage.Image, canvasImage.Canvas);

            var src   = ImageDataFactory.Create(canvasImage.ImagePath);
            var image = new iText.Layout.Element.Image(src, info.Left, info.Bottom);

            image.SetFixedPosition(info.Left, info.Bottom);
            image.ScaleAbsolute(info.ElementWidth, info.ElementHeight);

            return(image);
        }
예제 #27
0
        public CanvasImage CreateImage(int id, Rect extent, BitmapImage image)
        {
            var canvasImage = new CanvasImage()
            {
                Id     = id,
                X      = extent.X,
                Y      = extent.Y,
                Width  = extent.Width,
                Height = extent.Height,
                Image  = image
            };

            return(canvasImage);
        }
        public static async Task <WriteableBitmap> WriteToWriteableBitmapAsync(this ICanvasImage canvasImage,
                                                                               ICanvasResourceCreator canvasResourceCreator, Size size, float dpi)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new InMemoryRandomAccessStream())
            {
                await CanvasImage.SaveAsync(canvasImage, new Rect(new Point(0, 0), size), dpi, canvasResourceCreator,
                                            stream,
                                            CanvasBitmapFileFormat.Png);

                stream.Seek(0);
                return(await BitmapFactory.FromStream(stream));
            }
        }
예제 #29
0
    /// <summary>
    /// Mutates the underlying image.
    /// </summary>
    /// <param name="image">The canvas image.</param>
    /// <param name="action">The action that mutates the underlying image.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static CanvasImage Mutate(this CanvasImage image, Action <IImageProcessingContext> action)
    {
        if (image is null)
        {
            throw new ArgumentNullException(nameof(image));
        }

        if (action is null)
        {
            throw new ArgumentNullException(nameof(action));
        }

        image.Image.Mutate(action);
        return(image);
    }
예제 #30
0
        public void SetUp()
        {
            _controlSize = new Size();
            _viewExtent  = new Rect();
            _plot        = new PlotDto()
            {
                Id    = 1,
                X     = 1d,
                Y     = 2d,
                Color = new Domain.Colors.Color(0, 0, 0),
                Label = "Test",
                Image = new BitmapImage()
            };
            _plots = new List <PlotDto> {
                _plot
            };
            _canvasCircle = new CanvasCircle();
            _canvasImage  = new CanvasImage();
            _canvasLabel  = new CanvasLabel();

            _mockResizer = new Mock <IViewResizer>();
            _mockResizer.Setup(p => p.ResizeView(_controlSize, _viewExtent))
            .Returns(_viewExtent);

            _mockComputer = new Mock <IScaleComputer>();
            _mockComputer.Setup(p => p.ComputeScale(_controlSize, _viewExtent)).Returns(1d);

            _mockCalculator = new Mock <IGeometryCalculator>();

            _mockFactory = new Mock <IGeometryFactory>();
            _mockFactory.Setup(p => p.CreateCircle(_plot.Id, It.IsAny <Rect>(), It.IsAny <Color>()))
            .Returns(_canvasCircle);
            _mockFactory.Setup(p => p.CreateImage(_plot.Id, It.IsAny <Rect>(), _plot.Image))
            .Returns(_canvasImage);
            _mockFactory.Setup(p => p.CreateLabel(_plot.Id, It.IsAny <Point>(), _plot.Label))
            .Returns(_canvasLabel);

            _renderer = new PlotRenderer(
                _mockResizer.Object,
                _mockComputer.Object,
                _mockCalculator.Object,
                _mockFactory.Object);
        }
예제 #31
0
    void CreateItemsProgramatically()
    {
        // Adding image
        CanvasImage image = new CanvasImage (new Pixbuf (null, "logo.png"));
        image.Move (50, 50);
        canvas.Root.Add (image);

        // Adding textbox
        CanvasTextBox textbox = new CanvasTextBox();
        textbox.Move (50, 150);
        canvas.Root.Add (textbox);

        // Adding line
        Dia.CanvasLine line = new Dia.CanvasLine();
        line.LineWidth = 10;
        line.Color = 8327327;

        // Broke between 0.13 and 0.14
        // line.Dash = new double [] { 2, 4, 8, 16, 32 };

        line.HeadPos = new Dia.Point (50, 70);;
        line.TailPos = new Dia.Point (200, 250);
        line.Cap = Dia.CapStyle.Butt;
        line.Move (50, 150);
        canvas.Root.Add (line);

        // Adding box
        CanvasBox box = new CanvasBox();
        box.BorderWidth = 8.5;
        box.Color = 2134231;
        box.Move (250, 225);
        canvas.Root.Add (box);

        // Adding custom clock
        CanvasClock clock = new CanvasClock ();
        clock.Width = 100;
        clock.Height = 100;
        clock.Move (450, 225);
        canvas.Root.Add (clock);

        // Adding custom figure
        CanvasFigure figure = new CanvasFigure();
        figure.Move (50, 325);
        canvas.Root.Add (figure);

        view.UnselectAll();
        CanvasViewItem vitem = view.FindViewItem (image);
        view.Focus (vitem);
    }