private void Form1_Load(object sender, EventArgs e) { using (SKSurface surface = SKSurface.Create(make_image(500, 500))) { SKCanvas canvas = surface.Canvas; canvas.Clear(SKColors.Red); using (SKPaint paint = new SKPaint()) { paint.Color = SKColors.Blue; paint.IsAntialias = true; paint.StrokeWidth = 15; paint.Style = SKPaintStyle.Stroke; canvas.DrawCircle(50, 50, 30, paint); //arguments are x position, y position, radius, and paint } using (SKImage image = surface.Snapshot()) using (SKData data = image.Encode(SKEncodedImageFormat.Png, 500)) using (MemoryStream mStream = new MemoryStream(data.ToArray())) { Bitmap bm = new Bitmap(mStream, false); box.Image = bm; } } }
/// <summary> /// Updates the diagram view on the screen. /// <param name="clear">Clear the screen before redrawing?</param> /// </summary> public void UpdateScreen(bool clear) { try { SKSurface surf = CurrentDiagram.UpdateView(clear); using (SKImage screen = surf.Snapshot()) using (SKData data = screen.Encode(SKEncodedImageFormat.Png, 100)) using (Stream stream = data.AsStream()) { // The above using statement chain converts the SKSurface into a stream, // which can be used to make a Windows Forms-compatible Bitmap. Bitmap img = new Bitmap(stream, false); if (DiagramView.Image != null) { DiagramView.Image.Dispose(); } DiagramView.Image = img; } if (clear && !MessageBoxText.Contains(" Diagram view cleared and redrawn.")) { MessageBoxText += " Diagram view cleared and redrawn."; } } catch (Exception e) { Log.LogMessageError("Uncaught exception."); ErrorLogger.ShowErrorMessageBox(e); } }
public static System.Drawing.Bitmap Lines(SKSurface surface, int count) { float width = surface.Canvas.LocalClipBounds.Width; float height = surface.Canvas.LocalClipBounds.Height; surface.Canvas.DrawColor(new SKColor(0, 0, 0)); var paint = new SKPaint(); paint.IsAntialias = true; Random rand = new Random(); for (int i = 0; i < count; i++) { paint.Color = new SKColor((byte)rand.Next(255), (byte)rand.Next(255), (byte)rand.Next(255)); SKPoint pt0 = new SKPoint((float)(rand.NextDouble() * width), (float)(rand.NextDouble() * height)); SKPoint pt1 = new SKPoint((float)(rand.NextDouble() * width), (float)(rand.NextDouble() * height)); surface.Canvas.DrawLine(pt0, pt1, paint); } SKImage image = surface.Snapshot(); SKData data = image.Encode(SKEncodedImageFormat.Png, 100); MemoryStream mStream = new MemoryStream(data.ToArray()); var bmp = new System.Drawing.Bitmap(mStream, false); return(bmp); }
public void Build() { Generate(); var imageInfo = new SKImageInfo((int)_landscapeGenerator.ViewportWidth, 768); using SKSurface surface = SKSurface.Create(imageInfo); var canvas = surface.Canvas; // BASED ON (0,0) top left var paint = new SKPaint { Style = SKPaintStyle.Fill, Color = SKColors.Gray }; canvas.DrawRect(0, 0, imageInfo.Width, Landscaping.HeaderHeight, paint); _landscapeSky.Draw(canvas); _landscapeLand.Draw(canvas); _landscapeTerrain.Draw(canvas); using var image = surface.Snapshot(); using var data = image.Encode(SKEncodedImageFormat.Png, 100); using var stream = File.OpenWrite("screenshot.png"); data.SaveTo(stream); }
private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs e) { SKImageInfo info = e.Info; SKSurface surface = e.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); if (_pathToClip != null) { // Crop canvas before drawing image canvas.ClipPath(_pathToClip); } canvas.DrawBitmap(_originalBitmap, info.Rect); if (_pathToClip != null) { // Get cropped image byte array var snap = surface.Snapshot(); var data = snap.Encode(); _bytearray = data.ToArray(); ManualCropView.IsVisible = false; CropButton.IsVisible = false; DisplayCroppedButton.IsVisible = true; } }
public void UpdateWebImage() { SKCanvas canvas = Surface.Canvas; Surface.Canvas.Clear(Color.Gray.ToSKColor()); NodePaint = new SKPaint() { Style = SKPaintStyle.Fill, Color = ((Color)Application.Current.Resources["TraceColor"]).ToSKColor() }; LinePaint = new SKPaint() { Style = SKPaintStyle.Stroke, Color = ((Color)Application.Current.Resources["TraceColor"]).ToSKColor() }; Task[] tasks = new Task[WebNodes.Count]; int x = 0; foreach (WebNode node in WebNodes) { tasks[x++] = Task.Run(() => { canvas.DrawCircle((float)node.Position.X * PixelsPerPoint, (float)node.Position.Y * PixelsPerPoint, 4, NodePaint); foreach (WebNode node2 in WebNodes) { double DistanceSquared = Math.Abs(node.Position.Y - node2.Position.Y) * Math.Abs(node.Position.Y - node2.Position.Y) + Math.Abs(node.Position.X - node2.Position.X) * Math.Abs(node.Position.X - node2.Position.X); if (DistanceSquared < LinkLength.Value * LinkLength.Value) { canvas.DrawLine((float)node.Position.X * PixelsPerPoint, (float)node.Position.Y * PixelsPerPoint, (float)node2.Position.X * PixelsPerPoint, (float)node2.Position.Y * PixelsPerPoint, LinePaint); } } }); } Task.WaitAll(tasks); WebDisplay.UpdateImage(Surface.Snapshot()); }
protected override void OnPaintSurface(SKPaintSurfaceEventArgs e) { Trace.WriteLine($"{GetType().Name} OnPaintSurface"); SKImageInfo info = e.Info; SKSurface surface = e.Surface; SKCanvas canvas = surface.Canvas; using (var snap = surface.Snapshot()) { using (var paint = new SKPaint()) { Debug.WriteLine($"Source={Source.ToString()}"); if (Source is StreamImageSource) { // 一部だけ切り出そうにも土台のサイズがわからない StreamImageSource streamImageSource = (StreamImageSource)Source; CancellationToken cancellationToken = CancellationToken.None; Task <Stream> task = streamImageSource.Stream(cancellationToken); Stream stream = task.Result; var sKBitmap = SKBitmap.Decode(stream); paint.ImageFilter = SKImageFilter.CreateBlur(1, 1); canvas.DrawBitmap(sKBitmap, info.Rect, paint); } } } }
/// <summary> /// Tries to add an element to the current element, from the right. /// </summary> /// <param name="Element">Element to add.</param> /// <returns>Result, if understood, null otherwise.</returns> public override ISemiGroupElement AddRight(ISemiGroupElement Element) { if (!(Element is Graph G)) { return(null); } GraphSettings Settings = new GraphSettings() { Width = this.width, Height = this.height }; SKImage Bmp = G.CreateBitmap(Settings); if (this.bitmap is null) { return(new GraphBitmap(Bmp)); } using (SKSurface Surface = SKSurface.Create(new SKImageInfo(Math.Max(Bmp.Width, this.width), Math.Max(Bmp.Height, this.height), SKImageInfo.PlatformColorType, SKAlphaType.Premul))) { SKCanvas Canvas = Surface.Canvas; Canvas.DrawImage(this.bitmap, 0, 0); Canvas.DrawImage(Bmp, 0, 0); Bmp.Dispose(); return(new GraphBitmap(Surface.Snapshot())); } }
/// <summary> /// Encode output image as PDF /// </summary> /// <param name="surface"></param> /// <param name="width">Requested output width (pixels)</param> /// <param name="height">Requested output height (pixels)</param> /// <param name="q">Image quality (percentage)</param> /// <param name="pdfMetadata">Optional metadata to include in the PDF</param> /// <returns></returns> public static Stream EncodePdf(SKSurface surface, int width, int height, int q, Conf.PdfMetadata pdfMetadata) { // have to encode to JPEG then paint the encoded bytes, otherwise you get full JP2 quality var output = new MemoryStream(); var metadata = new SKDocumentPdfMetadata() { Creation = DateTime.Now, }; if (null != pdfMetadata) { metadata.Author = pdfMetadata.Author; } using (var skstream = new SKManagedWStream(output)) using (var writer = SKDocument.CreatePdf(skstream, metadata)) using (var snapshot = surface.Snapshot()) using (var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, q)) using (var image = SKImage.FromEncodedData(data)) using (var paint = new SKPaint()) { using (var canvas = writer.BeginPage(width, height)) { paint.FilterQuality = SKFilterQuality.High; canvas.DrawImage(image, new SKRect(0, 0, width, height), paint); writer.EndPage(); } } output.Seek(0, SeekOrigin.Begin); return(output); }
public object EndRender() { var image = _surface.Snapshot(); _surface.Dispose(); return(image); }
internal static Bitmap ColorizeImage(Bitmap baseImage, Color newColor, SKBlendMode blendMode, byte alpha = 255) { BitmapData data = baseImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.WriteOnly, baseImage.PixelFormat); var info = new SKImageInfo(baseImage.Width, baseImage.Height); using (SKSurface surface = SKSurface.Create(info, data.Scan0, baseImage.Width * 4)) using (SKImage image = SKImage.FromPixels(info, data.Scan0, baseImage.Width * 4)) using (var paint = new SKPaint()) { SKColor color = newColor.ToSKColor(); paint.Color = color; paint.BlendMode = SKBlendMode.SrcIn; surface.Canvas.DrawPaint(paint); using (SKImage img2 = surface.Snapshot()) { surface.Canvas.Clear(); paint.BlendMode = blendMode; paint.Color = new SKColor(color.Red, color.Green, color.Blue, alpha); surface.Canvas.DrawImage(image, SKRect.Create(image.Width, image.Height)); surface.Canvas.DrawImage(img2, SKRect.Create(img2.Width, img2.Height), paint); } } baseImage.UnlockBits(data); return(baseImage); }
private void Draw(SKSurface surface, double scale) { var canvas = surface.Canvas; surface.Canvas.Clear(CanvasBackgroundColor.ToSkiaColor()); _gridRenderer.Render(canvas, scale); if (ToolCollection == null) { return; } _backgroundImageRenderer.Render(canvas, scale); foreach (var geom in ToolCollection.Geometries) { GeometryRenderer.Render(canvas, geom, scale); } //TODO Try to do this on demand, rather than every draw... // Snapshotting without encoding is rather fast though and does not impact performance that much SnapShot = surface.Snapshot(); //TODO Look into this // Not really needed, but keeps the memory slightly lower and does not impact performance that much var mem = GC.GetTotalMemory(true); System.Diagnostics.Debug.WriteLine($"Mem {mem}"); }
private void CreateResizedImage() { using var image = _surface.Snapshot(); var boundary = SKRectI.Create(0, 0, Width, Height); Result = image.Subset(boundary); }
static void Main(string[] args) { Random rand = new Random(); // set up the image SKImageInfo imageInfo = new SKImageInfo(800, 600, SKColorType.Rgb888x, SKAlphaType.Premul); SKSurface surface = SKSurface.Create(imageInfo); SKCanvas canvas = surface.Canvas; // draw some lines canvas.Clear(SKColor.Parse("#003366")); var paint = new SKPaint { Color = new SKColor(255, 255, 255, 123), IsAntialias = true }; for (int i = 0; i < 1000; i++) { SKPoint ptA = new SKPoint(rand.Next(imageInfo.Width), rand.Next(imageInfo.Height)); SKPoint ptB = new SKPoint(rand.Next(imageInfo.Width), rand.Next(imageInfo.Height)); canvas.DrawLine(ptA, ptB, paint); } // save the output string filename = System.IO.Path.GetFullPath("test.png"); System.IO.Stream fileStream = System.IO.File.OpenWrite(filename); SKImage snap = surface.Snapshot(); SKData encoded = snap.Encode(SKEncodedImageFormat.Png, 100); encoded.SaveTo(fileStream); Console.WriteLine($"Saved: {filename}"); }
private void skiascreen_PaintSurface(object sender, SKPaintSurfaceEventArgs e) { if (surface != null) { e.Surface.Canvas.DrawImage(surface.Snapshot(), 0, 0); } }
public void Close() { canvas.ClipPath(clip, SKClipOperation.Intersect, true); canvas.DrawImage(SKImage.FromBitmap(noise), new SKPoint(0, 0)); canvas.DrawImage(surface.Snapshot(), new SKPoint(0, 0), paint); canvas.Restore(); }
public void WriteAsPng(Stream stream) { using (var image = surface.Snapshot()) using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) { data.SaveTo(stream); } }
// Draw on canvas void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; // Initialize canvas if resetcanvas is true if (resetcanvas) { // Delete paths while (paths.Count > 0) { paths.RemoveAt(0); } // Clear canvas in white canvas.Clear(SKColors.White); // Reset flag for erasing canvas resetcanvas = false; } // Draw all paths (if resetcanvas is not set) else { // Define paint brush var touchPathStroke = new SKPaint { IsAntialias = true, Style = SKPaintStyle.Stroke, Color = SKColors.Black, StrokeWidth = 0.05f * Math.Min(info.Width, info.Height), StrokeCap = SKStrokeCap.Round }; // Draw paths (currently "in drawing" and finalized) foreach (var touchPath in temporaryPaths) { canvas.DrawPath(touchPath.Value, touchPathStroke); } foreach (var touchPath in paths) { canvas.DrawPath(touchPath, touchPathStroke); } } // Save canvas to bitmap in page "CameraTestPage" // This coding is not elegant / robust but it works if (savetobitmap) { Application app = Application.Current; CameraTestPage page = app.MainPage.Navigation.NavigationStack[1] as CameraTestPage; var image = surface.Snapshot(); page.bitmap = SKBitmap.FromImage(image); savetobitmap = false; } }
private static Stream ToStream(SKSurface surface) { var stream = new MemoryStream(); using var image = surface.Snapshot(); using var data = image.Encode(SKEncodedImageFormat.Png, 100); data.SaveTo(stream); stream.Seek(0, SeekOrigin.Begin); return(stream); }
private SKCanvas _image => _surface.Canvas;//_rec.RecordingCanvas;//_surface.Canvas; public byte[] WriteImage() { /* * return SKImage.FromPicture(_rec.EndRecording(), * new SKSizeI((int)_rec.RecordingCanvas.LocalClipBounds.Width, * (int)_rec.RecordingCanvas.LocalClipBounds.Height)) * .Encode().ToArray(); */ return(_surface.Snapshot().Encode().ToArray()); }
private async Task <ModifiedImage> SaveImageAsPng(SKSurface surface) { using (var encodedImage = surface.Snapshot()) { return(await Task.Run(() => { var data = encodedImage.Encode(SKEncodedImageFormat.Png, 0); return new ModifiedImage("image/png", data.ToArray()); })); } }
private void OnPainting(object sender, SKPaintSurfaceEventArgs args) { try { // CLEARING THE SURFACE // we get the current surface from the event args SKSurface surface = args.Surface; // then we get the canvas that we can draw on var canvas = surface.Canvas; //// clear the canvas / view canvas.Clear(SKColors.White); if (imageLoaded != null) { var libraryBitmap = SKBitmap.Decode(imageLoaded.Path); SKImageInfo info = args.Info; float x = (info.Width - libraryBitmap.Width) / 2; float y = (info.Height / 2 - libraryBitmap.Height) / 2; canvas.DrawBitmap(libraryBitmap, x, y); } // create the paint for the touch path var touchPathStroke = new SKPaint { IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 5 }; // draw the paths foreach (var touchPath in temporaryPaths) { touchPathStroke.Color = touchPath.Value.Color; canvas.DrawPath(touchPath.Value, touchPathStroke); } foreach (var touchPath in paths) { touchPathStroke.Color = touchPath.Color; canvas.DrawPath(touchPath, touchPathStroke); } var snap = surface.Snapshot(); pngImage = snap.Encode(); } catch (Exception ex) { } }
private async Task <ModifiedImage> SaveImageAsJpeg(SKSurface surface, int quality = 100) { using (var encodedImage = surface.Snapshot()) { return(await Task.Run(() => { var data = encodedImage.Encode(SKEncodedImageFormat.Jpeg, quality); return new ModifiedImage("image/jpeg", data.ToArray()); })); } }
private static Stream Encode(SKSurface surface, int width, int height, EncodingStrategy encodingStrategy, ImageFormat format, int q, Conf.PdfMetadata pdfMetadata, ushort horizontalResolution, ushort verticalResolution) { switch (encodingStrategy) { case EncodingStrategy.Skia: FormatLookup.TryGetValue(format, out SKEncodedImageFormat formatType); return(EncodeSkiaImage(surface, formatType, q, horizontalResolution, verticalResolution)); case EncodingStrategy.PDF: return(EncodePdf(surface, width, height, q, pdfMetadata)); case EncodingStrategy.JPEG2000: return(Jpeg2000.Compressor.Compress(surface.Snapshot())); case EncodingStrategy.Tifflib: return(Image.Tiff.TiffEncoder.Encode(surface.Snapshot())); default: throw new ArgumentException("Unsupported format", "format"); } }
public static SKImage CropSurfaceToImage(SKSurface skSurface, int imageCanvasSize, int destSize, SKPaint paint) { SKImage skImage = null; var srcImage = skSurface.Snapshot(); using (var newSurface = SKSurface.Create(new SKImageInfo(destSize, destSize))) { newSurface.Canvas.DrawImage(srcImage, SKRect.Create(0, 0, destSize, destSize), SKRect.Create(0, 0, destSize, destSize), paint); newSurface.Canvas.Flush(); skImage = newSurface.Snapshot(); } return(skImage); }
/// <summary> /// Returns a new resized image. /// </summary> public Image Resize(double width, double height) { using (SKSurface surface = SKSurface.Create(new SKImageInfo((int)(width * RenderProps.DisplayScale), (int)(height * RenderProps.DisplayScale), SKImageInfo.PlatformColorType, SKAlphaType.Premul))) using (SKPaint paint = new SKPaint()) { paint.IsAntialias = true; paint.FilterQuality = SKFilterQuality.High; surface.Canvas.DrawImage(Bitmap, new SKRectI(0, 0, (int)(width * RenderProps.DisplayScale), (int)(height * RenderProps.DisplayScale)), paint); surface.Canvas.Flush(); return(new Image(FilePath, surface.Snapshot())); } }
public void initialize(string argument) { this.Size = new Size(500, 500); this.StartPosition = FormStartPosition.CenterScreen; this.MaximumSize = new Size(500, 500); this.MinimumSize = new Size(500, 500); try { image_info = new SKImageInfo(width, height); surface = SKSurface.Create(image_info); canvas = surface.Canvas; canvas.Clear(SKColors.White); coordinates_lines_paint = new SKPaint(); coordinates_lines_paint.Color = SKColor.Parse("#d55e00"); coordinates_lines_paint.IsAntialias = true; coordinates_lines_paint.StrokeWidth = 1; coordinates_lines_paint.Style = SKPaintStyle.Stroke; graph_paint = new SKPaint(); graph_paint.Color = SKColors.Black; graph_paint.IsAntialias = true; graph_paint.StrokeWidth = 1; graph_paint.Style = SKPaintStyle.Stroke; //points = get_points(-198, height); coordinates_lines = new SKPath(); graph = new SKPath(); points = coordinates(); graph_coordinates_lines(); graph_lines(points); canvas.DrawPath(coordinates_lines, coordinates_lines_paint); canvas.DrawPath(graph, graph_paint); image = surface.Snapshot(); data = image.Encode(SKEncodedImageFormat.Png, 500); memory_stream = new MemoryStream(data.ToArray()); bitmap = new Bitmap(memory_stream, false); this.BackgroundImage = bitmap; this.BackgroundImageLayout = ImageLayout.None; delete_data(); } catch (System.Exception error) { Console.WriteLine("" + error); } }
public virtual Stream Generate(int width, int height) { SKImageInfo imageInfo = new SKImageInfo(width, height); using (SKSurface surface = SKSurface.Create(imageInfo)) { SKCanvas canvas = surface.Canvas; canvas.Clear(); drawChart(canvas, width, height); var img = surface.Snapshot(); var data = img.Encode(SKEncodedImageFormat.Png, 100); return(data.AsStream(false)); } }
public static SKImage ScaleSurfaceToImage(SKSurface skSurface, int imageCanvasSize, int destSize, SKPaint paint) { SKImage skImage = null; var canvas = skSurface.Canvas; // scale if (destSize == imageCanvasSize) { skImage = skSurface.Snapshot(); } else { // 先缩放;然后绘制到小图上面,即相当于Crop了 canvas.Scale(1.0f * destSize / imageCanvasSize); var srcImage = skSurface.Snapshot(); using (var newSurface = SKSurface.Create(new SKImageInfo(destSize, destSize))) { newSurface.Canvas.DrawImage(srcImage, SKRect.Create(0, 0, imageCanvasSize, imageCanvasSize), SKRect.Create(0, 0, destSize, destSize), paint); newSurface.Canvas.Flush(); skImage = newSurface.Snapshot(); } } // scale return(skImage); }
public static Stream EncodeSkiaImage(SKSurface surface, SKEncodedImageFormat format, int q, ushort horizontalResolution, ushort verticalResolution) { var output = new MemoryStream(); using (var image = surface.Snapshot()) { var data = image.Encode(format, q); if (format == SKEncodedImageFormat.Jpeg) { SetJpgDpi(data.Data, horizontalResolution, verticalResolution); } var ms = data.AsStream(false); ms.Seek(0, SeekOrigin.Begin); return(ms); } }