Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 88 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,88 @@
# How-to-Export-Chart-as-Image-in-WinUI-Chart
How to Export Chart as Image in WinUI Chart
# How to Export Chart as Image in WinUI Chart
This article provides a detailed walkthrough on how to export a [WinUI Cartesian Chart](https://www.syncfusion.com/winui-controls/cartesian-charts) as an image. You can export the chart view in your desired file format, with supported formats being **JPEG** and **PNG.**

### Initialize SfCartesianChart:

Set up the **SfCartesianChart** following the [ Syncfusion WinUI Cartesian Chart documentation.](https://help.syncfusion.com/winui/cartesian-charts/getting-started)
```xml
<StackPanel Orientation="Vertical">
<chart:SfCartesianChart x:Name="Chart" Background="White" IsTransposed="True"
Header="Daily Water Consumption Tracking">
....
<chart:ColumnSeries ItemsSource="{Binding DailyWaterIntake}"
XBindingPath="Day"
YBindingPath="Liters"
ShowDataLabels="True">
<chart:ColumnSeries.DataLabelSettings>
<chart:CartesianDataLabelSettings Position="Inner"/>
</chart:ColumnSeries.DataLabelSettings>
</chart:ColumnSeries>
</chart:SfCartesianChart>

<Button x:Name="button" Content="Export as Image" Click="Button_Click" />
</StackPanel>
```

### Export the Chart as an Image:

```csharp
private async void Button_Click(object sender, RoutedEventArgs e)
{
await SaveAsImageAsync(Chart, "chart.png");
}

private async Task SaveAsImageAsync(SfCartesianChart chart, string fileName)
{
if (chart == null)
return;

// Render the chart to a RenderTargetBitmap
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(chart);

// Get pixel data
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();

// Determine file format and encoder
string extension = Path.GetExtension(fileName)?.ToLower() ?? ".png";
var encoderId = extension == ".jpg" || extension == ".jpeg"
? BitmapEncoder.JpegEncoderId
: BitmapEncoder.PngEncoderId;

// Choose image save path
var folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(@"D:\");
var picturesFolder = await folder.CreateFileAsync( fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

// Encode the image
using (var stream = await picturesFolder.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);

encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
96.0, // DPI X
96.0, // DPI Y
pixels);

await encoder.FlushAsync();
}
}
```

**Note:** By default, the chart background is transparent. When using JPEG format, RenderTargetBitmap converts the transparent background to black. To resolve this, set the chart’s BackgroundColor to white or any preferred color.

**Chart output**

![Chart-WinUI.png](https://support.syncfusion.com/kb/agent/attachment/article/18644/inline?token=eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjM0MjM0Iiwib3JnaWQiOiIzIiwiaXNzIjoic3VwcG9ydC5zeW5jZnVzaW9uLmNvbSJ9.0wMM_ZaV1z0RXFn8efmG0bKwTOt6QMiZ7DQ5fa1QLyU)

**Exported Chart Image**

![chart.png](https://support.syncfusion.com/kb/agent/attachment/article/18644/inline?token=eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjM0MjMyIiwib3JnaWQiOiIzIiwiaXNzIjoic3VwcG9ydC5zeW5jZnVzaW9uLmNvbSJ9.VhSO304zS7VSvBDSySJWOBxdySgRK0LWuAdmx3Vl4No)

### KB link
For a more detailed, refer to the [Export Chart View as Image KB.](https://support.syncfusion.com/agent/kb/18644)

40 changes: 40 additions & 0 deletions WinUISampleDemo/WinUISampleDemo.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinUISampleDemo", "WinUISampleDemo\WinUISampleDemo.csproj", "{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|ARM64.ActiveCfg = Debug|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|ARM64.Build.0 = Debug|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|ARM64.Deploy.0 = Debug|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x64.ActiveCfg = Debug|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x64.Build.0 = Debug|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x64.Deploy.0 = Debug|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x86.ActiveCfg = Debug|x86
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x86.Build.0 = Debug|x86
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Debug|x86.Deploy.0 = Debug|x86
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|ARM64.ActiveCfg = Release|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|ARM64.Build.0 = Release|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|ARM64.Deploy.0 = Release|ARM64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x64.ActiveCfg = Release|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x64.Build.0 = Release|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x64.Deploy.0 = Release|x64
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x86.ActiveCfg = Release|x86
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x86.Build.0 = Release|x86
{0C10A7EF-1D8E-48E0-A15A-D865C3FA5F58}.Release|x86.Deploy.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
16 changes: 16 additions & 0 deletions WinUISampleDemo/WinUISampleDemo/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Application
x:Class="WinUISampleDemo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WinUISampleDemo">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
<!-- Other merged dictionaries here -->
</ResourceDictionary.MergedDictionaries>
<!-- Other app resources here -->
</ResourceDictionary>
</Application.Resources>
</Application>
50 changes: 50 additions & 0 deletions WinUISampleDemo/WinUISampleDemo/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.UI.Xaml.Shapes;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace WinUISampleDemo
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
}

/// <summary>
/// Invoked when the application is launched.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
m_window = new MainWindow();
m_window.Activate();
}

private Window? m_window;
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added WinUISampleDemo/WinUISampleDemo/Assets/StoreLogo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
40 changes: 40 additions & 0 deletions WinUISampleDemo/WinUISampleDemo/MainWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="WinUISampleDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:chart="using:Syncfusion.UI.Xaml.Charts"
xmlns:local="using:WinUISampleDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="WinUISampleDemo">

<StackPanel Orientation="Vertical" Margin="20">
<chart:SfCartesianChart Background="White" x:Name="Chart" Height="500" IsTransposed="True" Header="Daily Water Consumption Tracking">

<chart:SfCartesianChart.DataContext>
<local:ViewModel/>
</chart:SfCartesianChart.DataContext>

<chart:SfCartesianChart.XAxes>
<chart:CategoryAxis Header="Days" PlotOffsetEnd="20"/>
</chart:SfCartesianChart.XAxes>

<chart:SfCartesianChart.YAxes>
<chart:NumericalAxis Header="In Liters" Maximum="4.4"/>
</chart:SfCartesianChart.YAxes>

<chart:ColumnSeries ItemsSource="{Binding DailyWaterIntake}"
XBindingPath="Day"
YBindingPath="Liters"
ShowDataLabels="True">
<chart:ColumnSeries.DataLabelSettings>
<chart:CartesianDataLabelSettings Position="Inner"/>
</chart:ColumnSeries.DataLabelSettings>
</chart:ColumnSeries>
</chart:SfCartesianChart>
<Button x:Name="button" Content="Export as Image" Click="Button_Click" HorizontalAlignment="Center"
VerticalAlignment="Center" Background="#0099cc" Margin="0,20,0,0"/>
</StackPanel>
</Window>
87 changes: 87 additions & 0 deletions WinUISampleDemo/WinUISampleDemo/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;

using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.UI.Xaml.Navigation;

using Syncfusion.UI.Xaml.Charts;

using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Imaging;
using Windows.Storage;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace WinUISampleDemo
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
await SaveAsImageAsync(Chart, "chart.png");
}

private async Task SaveAsImageAsync(SfCartesianChart chart, string fileName)
{
if (chart == null)
return;

// Render the chart to a RenderTargetBitmap
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(chart);

// Get pixel data
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();

// Determine file format and encoder
string extension = Path.GetExtension(fileName)?.ToLower() ?? ".png";
var encoderId = extension == ".jpg" || extension == ".jpeg"
? BitmapEncoder.JpegEncoderId
: BitmapEncoder.PngEncoderId;

// Choose image save path
var folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(@"D:\");
var picturesFolder = await folder.CreateFileAsync( fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);


// Encode the image
using (var stream = await picturesFolder.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(encoderId, stream);

encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
96.0, // DPI X
96.0, // DPI Y
pixels);

await encoder.FlushAsync();
}
}
}
}
51 changes: 51 additions & 0 deletions WinUISampleDemo/WinUISampleDemo/Package.appxmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>

<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap rescap">

<Identity
Name="c6b45550-53b2-4e2f-8810-b136147c96c7"
Publisher="CN=SowndharyaSelladurai"
Version="1.0.0.0" />

<mp:PhoneIdentity PhoneProductId="c6b45550-53b2-4e2f-8810-b136147c96c7" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

<Properties>
<DisplayName>WinUISampleDemo</DisplayName>
<PublisherDisplayName>SowndharyaSelladurai</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>

<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
</Dependencies>

<Resources>
<Resource Language="x-generate"/>
</Resources>

<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="$targetentrypoint$">
<uap:VisualElements
DisplayName="WinUISampleDemo"
Description="WinUISampleDemo"
BackgroundColor="transparent"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>

<Capabilities>
<rescap:Capability Name="runFullTrust" />
</Capabilities>
</Package>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishProtocol>FileSystem</PublishProtocol>
<Platform>ARM64</Platform>
<RuntimeIdentifier>win-arm64</RuntimeIdentifier>
<PublishDir>bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\</PublishDir>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
</PropertyGroup>
</Project>
Loading
Loading