// -------------------------------------------------------------------------------------------------------------------- // // Copyright (c) 2020 OxyPlot contributors // // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.SkiaSharp { using global::SkiaSharp; using System.IO; /// /// Provides functionality to export plots to jpeg using the SkiaSharp renderer. /// public class JpegExporter : IExporter { /// /// Gets or sets the DPI. /// public float Dpi { get; set; } = 96; /// /// Gets or sets the export height (in pixels). /// public int Height { get; set; } /// /// Gets or sets the export width (in pixels). /// public int Width { get; set; } /// /// Gets or sets the export quality (0-100). /// public int Quality { get; set; } = 90; /// /// Exports the specified model to a file. /// /// The model. /// The path. /// The width (points). /// The height (points). /// The export quality (0-100). /// The DPI (dots per inch). public static void Export(IPlotModel model, string path, int width, int height, int quality, float dpi = 96) { using var stream = File.OpenWrite(path); Export(model, stream, width, height, quality, dpi); } /// /// Exports the specified model to a stream. /// /// The model. /// The output stream. /// The width (points). /// The height (points). /// The export quality (0-100). /// The DPI (dots per inch). public static void Export(IPlotModel model, Stream stream, int width, int height, int quality, float dpi = 96) { var exporter = new JpegExporter { Width = width, Height = height, Quality = quality, Dpi = dpi }; exporter.Export(model, stream); } /// public void Export(IPlotModel model, Stream stream) { using var bitmap = new SKBitmap(this.Width, this.Height); using (var canvas = new SKCanvas(bitmap)) using (var context = new SkiaRenderContext { RenderTarget = RenderTarget.PixelGraphic, SkCanvas = canvas }) { canvas.Clear(SKColors.White); var dpiScale = this.Dpi / 96; context.DpiScale = dpiScale; model.Update(true); var backgroundColor = model.Background; // jpg doesn't support transparency if (!backgroundColor.IsVisible()) { backgroundColor = OxyColors.White; } canvas.Clear(backgroundColor.ToSKColor()); model.Render(context, new OxyRect(0, 0, this.Width / dpiScale, this.Height / dpiScale)); } using var skStream = new SKManagedWStream(stream); bitmap.Encode(skStream, SKEncodedImageFormat.Jpeg, this.Quality); } } }