C# Saving Live Chart to PNG in WinForms - c#

I am having difficulties in exporting LiveCharts PieChart to a .png file.
So far what I have done is trying to draw the control to a bitmap (DrawToBitmap), but it is just outputting a black image. I have discarded other alternatives such as screenshots because the chart is not created to be deployed in a custom form for visualization. Its main purpose is just graphic statistic exporting.
This is my main code:
LiveCharts.WinForms.PieChart chart = initializePieChart2DFolder(true);
Bitmap bmp = new Bitmap(chart.Width, chart.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save("graphFolder.png", System.Drawing.Imaging.ImageFormat.Png);
This is the method I use to create the Pie chart:
private LiveCharts.WinForms.PieChart initializePieChart2DFolder()
{
LiveCharts.WinForms.PieChart chart = new LiveCharts.WinForms.PieChart();
chart.Anchor = System.Windows.Forms.AnchorStyles.None;
chart.Location = new System.Drawing.Point(17, 56);
chart.Name = "pieChart2DFolder";
chart.Size = new System.Drawing.Size(364, 250);
chart.TabIndex = 0;
chart.BackColorTransparent = false;
chart.BackColor = Color.White;
chart.ForeColor = Color.Black;
SeriesCollection chartData = new SeriesCollection();
foreach(var annot in numAnnotsPerLabel)
{
System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color[annot.Key].A, color[annot.Key].R, color[annot.Key].G, color[annot.Key].B);
chartData.Add( new PieSeries { Title = annot.Key,
Values = new ChartValues<int> { annot.Value },
DataLabels = true,
Stroke = System.Windows.Media.Brushes.DimGray,
Foreground = System.Windows.Media.Brushes.Black,
FontSize = 9,
Fill = new
System.Windows.Media.SolidColorBrush(newColor)});
}
chart.Series = chartData;
DefaultLegend customLegend = new DefaultLegend();
customLegend.BulletSize = 15;
customLegend.Foreground = System.Windows.Media.Brushes.Black;
customLegend.Orientation = System.Windows.Controls.Orientation.Vertical;
customLegend.FontSize = 10;
chart.DefaultLegend = customLegend;
chart.LegendLocation = LegendLocation.Right;
var tooltip = chart.DataTooltip as DefaultTooltip;
tooltip.SelectionMode = LiveCharts.TooltipSelectionMode.OnlySender;
return chart;
}
Thank you very much in advance!

Related

chart.DrawToBitmap blank

I have some code that uses System.Windows.Forms.DataVisualization.Charting; to generate a chart and create a bitmap image
private Bitmap GetTargetGradingImage(int sessionsTrained, int target, int height, int width)
{
const string TargetSeries = "TargetSeries";
var chart = new Chart
{
Height = height,
Width = width
};
chart.ChartAreas.Add(new ChartArea()
{
Name = "ChartArea1"
});
chart.Series.Clear();
chart.Series.Add(new Series()
{
Name = TargetSeries,
IsVisibleInLegend = true,
ChartType = SeriesChartType.Column,
Color = Color.Green
});
chart.Series[TargetSeries].ChartArea = chart.ChartAreas[0].Name;
string[] XPointMember = new string[2];
int[] YPointMember = new int[2];
XPointMember[0] = "Sessions";
YPointMember[0] = sessionsTrained;
XPointMember[1] = "Target";
YPointMember[1] = target;
chart.Series[TargetSeries].Points.DataBindXY(XPointMember, YPointMember);
chart.Invalidate();
var bitmap = new Bitmap(chart.Size.Width, chart.Size.Height, PixelFormat.Format32bppArgb);
chart.DrawToBitmap(bitmap, chart.Bounds);
//chart.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height));
return bitmap;
}
This works fine on my dev system but not when published to an Azure website. The images are blank.
The images are being used for inclusion in html emails.
Any ideas?
Cracked it.
Didn't need the chart.DrawToBitmap bit at all
This works
using (var chartImage = new MemoryStream())
{
chart.SaveImage(chartImage, ChartImageFormat.Png);
targetBuf = Convert.ToBase64String(chartImage.ToArray());
}
This gives me a Base64 encoded string that I can use in an img tag

C# Creating Custom Chart Class

It's been a while since I did something like this, however I am trying to create a custom chart class derived from the DataVisualization.Chart class,
I have the following
public class clsCustomChart:System.Windows.Forms.DataVisualization.Charting.Chart
{
public clsCustomChart(string strChartTitle, double[] dblX, double[] dblY)
{
// Create the chart
// Create the chart
Chart chartReturn = new Chart();
chartReturn.BackColor = Color.FromArgb(50, Color.DarkGray);
chartReturn.BorderlineDashStyle = ChartDashStyle.Solid;
chartReturn.BorderlineColor = Color.Black;
chartReturn.Width = 300;
chartReturn.Height = 300;
// Create the legend
Legend l = new Legend("Legend");
l.Docking = Docking.Bottom;
l.BackColor = Color.Transparent;
chartReturn.Legends.Add(l);
// Create the chart area
ChartArea a = new ChartArea("ChartArea1");
a.Area3DStyle.Enable3D = false;
a.Area3DStyle.WallWidth = 0;
a.BackColor = Color.FromArgb(100, Color.Black);
chartReturn.ChartAreas.Add(a);
// Create the axis
a.AxisX.LineColor = Color.Silver;
a.AxisX.MajorGrid.Enabled = true;
a.AxisX.MinorGrid.Enabled = false;
a.AxisX.MajorGrid.LineColor = Color.FromArgb(50, Color.Black);
a.AxisX.LabelStyle.Font = new System.Drawing.Font("Arial", 8F);
a.AxisY.LineColor = Color.Silver;
a.AxisY.MajorGrid.Enabled = true;
a.AxisY.MinorGrid.Enabled = false;
a.AxisY.MajorGrid.LineColor = Color.FromArgb(50, Color.Black);
a.AxisY.LabelStyle.Font = new System.Drawing.Font("Arial", 8F);
// Chart title
chartReturn.Titles.Add(new Title(strChartTitle));
// Add the data
// Create the data series
Series s = new Series("IN");
s.ChartType = SeriesChartType.Line;
dblX.ToList<double>().ForEach(x => { s.Points.Add(x); });
s.Color = Color.FromArgb(200, Color.Red);
s.BorderWidth = 3;
Series s2 = new Series("OUT");
s2.ChartType = SeriesChartType.Line;
dblY.ToList<double>().ForEach(x => { s2.Points.Add(x); });
s2.Color = Color.FromArgb(200, Color.Green);
s2.BorderWidth = 3;
chartReturn.Series.Add(s);
chartReturn.Series.Add(s2);
chartReturn.SaveImage("c:/test/" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".jpeg", ChartImageFormat.Jpeg);
}
}
The code that is in the custom chart is all tested and working fine, when creating as a chart object, and the custom class saves the chart as image fine.
However, when I try this in a form
Chart C = (Chart)new clsCustomChart("TEST",x,y);
this.Controls.Add(C);
I don't get the chart...... can anyone advise.....
TIA
// Create the chart
Chart chartReturn = new Chart();
This creates a chart which you then style and throw away.
Delete it and replace chartReturn with this!
Also you may want to provide a parameterless constructor in case you ever want to place it on a form via the designer..

Pixelated text chart using Charting Library in ASP

I want to create a chart with this Library, I have created one but the text is pixelated so the feel is very ugly.
I'm passing this charts to a PDF file with iText Sharp to create a report.
Here is the code:
private static byte[] ObtenerBarraDoble(IList<ValorBarraDTO> valores)
{
var newColor1 = Color.FromArgb(187, 189, 191);
var newColor2 = Color.FromArgb(0, 138, 209);
using (var graficoPie = new Chart { Height = 200, Width = 600, RenderType = RenderType.BinaryStreaming })
{
var chartAreaPie = new ChartArea();
chartAreaPie.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
chartAreaPie.AxisX.MajorGrid.LineColor = Color.White;
chartAreaPie.AxisY.MajorGrid.LineColor = Color.White;
chartAreaPie.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 2);
chartAreaPie.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 2);
graficoPie.ChartAreas.Add(chartAreaPie);
var serieNuevo = new Series("Cartera Actual")
{
ChartType = SeriesChartType.Column,
XValueMember = "label",
YValueMembers = "valor1",
Color = newColor1,
Legend = "Cartera Actual",
IsValueShownAsLabel = true,
};
graficoPie.Series.Add(serieNuevo);
var serie = new Series("Cartera Recomendada")
{
ChartType = SeriesChartType.Column,
XValueMember = "label",
YValueMembers = "valor2",
Color = newColor2,
Legend = "Cartera Propuesta",
IsValueShownAsLabel =true,
};
graficoPie.Series.Add(serie);
graficoPie.DataSource = valores;
return PdfHelper.ChartABinario(graficoPie);
}
}
Here is ChartABinario method:
internal static byte[] ChartABinario(Chart graficoPie)
{
using (var ms = new MemoryStream())
{
graficoPie.SaveImage(ms, ChartImageFormat.Png);
byte[] retorno = ms.ToArray();
return retorno;
}
}
This creates the chart and it's displaying it well, but the text is bad. What can I do to make that the text doesn't display pixelated letters?

WriteableBitmap.SaveJpeg renders a black image (WP7)

I'm trying to render some text and an image to a writeable bitmap to make 1 larger image, and this method has worked in other locations for creating or manipulating images, but for some reason, this instance is only creating a black image. If I just set the image source to the original WriteableBitmap, it shows just fine, but when I call SaveJpeg and then LoadJpeg, it shows as a black image (and yes, I need to call SaveJpeg since this is actually getting passed up to a server). The following is how I'm trying to render the elements:
NoteViewModel note = Instance.Note;
var grid = new Grid()
{
Height = 929,
Width = 929
};
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(679) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
var noteText = new TextBlock()
{
Text = note.Text,
FontFamily = note.FontFamily,
Foreground = note.FontColor,
TextWrapping = System.Windows.TextWrapping.Wrap,
Width = 929,
Height = 679
};
Grid.SetRow(noteText, 0);
grid.Children.Add(noteText);
WriteableBitmap sigImage = Instance.Signature.SignatureImage;
var sig = new Image()
{
Source = sigImage,
Height = 250,
Width = (sigImage.PixelWidth / sigImage.PixelHeight) * 250,
Margin = new Thickness(929 - ((sigImage.PixelWidth / sigImage.PixelHeight) * 250), 0, 0, 0)
};
Grid.SetRow(sig, 1);
grid.Children.Add(sig);
var messagePicture = new WriteableBitmap(grid, null);
var stream = new MemoryStream();
messagePicture.SaveJpeg(stream, messagePicture.PixelWidth, messagePicture.PixelHeight, 0, 100); //Save to a temp stream
stream.Position = 0;
var test = new WriteableBitmap(929,929); //Load the picture back up to see it
test.LoadJpeg(stream);
img.Source = test; //Show the image on screen (img is an Image element)
So apparently WriteableBitmap will render a transparent background as black when calling SaveJpeg, so I solved this by rendering a white canvas as well, like so:
var background = new Canvas()
{
Width = 929,
Height = 929,
Background = new SolidColorBrush(Colors.White)
};
messagePicture.Render(background, new TranslateTransform());

Issues regarding image and random row color for a table in openxml?

I'm using an HTML to OpenXML convertor, gridview HTML code is assigned to a stringbuilder. Using that we convert that HTML to OpenXML, but when it comes to word the following below issues are found.
I have to fill background of a row of a table with grainsboro color but only text background is filled and not cell completely.
I wanted to align the image of the header to the right.
This is an asp.net application done in C#
A***building image code plz tell me how to align the image to right***
d=DocumentFormat.OpenXml.Drawing;
int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL);
int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL);
Drawing drawing = new Drawing();
d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 130, DistanceFromBottom = 430, DistanceFromLeft = 260, DistanceFromRight = 330 };
d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 };
d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 };
d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight };
d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName };
d.Wordprocessing.HorizontalPosition h = new d.Wordprocessing.HorizontalPosition(new d.Wordprocessing.HorizontalAlignment("right"));
d.Graphic graphic = new d.Graphic();
// We don’t have to hard code a URI anywhere else in the document but if we don’t do it here
// we end up with a corrupt document.
d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI };
d.Pictures.Picture pic = new d.Pictures.Picture();
d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties();
d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName };
d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties();
d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill();
d.Blip blip = new d.Blip { Embed = imageRelationshipID };
d.Stretch stretch = new d.Stretch();
d.FillRectangle fillRect = new d.FillRectangle();
d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties();
d.Transform2D xfrm = new d.Transform2D();
d.Offset off = new d.Offset { X = 0, Y = 0 };
d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight };
d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle };
d.AdjustValueList avLst = new d.AdjustValueList();
xfrm.Append(off);
xfrm.Append(ext);
prstGeom.Append(avLst);
stretch.Append(fillRect);
spPr.Append(xfrm);
spPr.Append(prstGeom);
blipFill.Append(blip);
blipFill.Append(stretch);
nvPicPr.Append(cNvPr);
nvPicPr.Append(cNvPicPr);
pic.Append(nvPicPr);
pic.Append(blipFill);
pic.Append(spPr);
graphicData.Append(pic);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(docPr);
inline.Append(graphic);
//anchor.Append(extent);
//anchor.Append(docPr);
//anchor.Append(h);
//anchor.Append(graphic);
drawing.Append(inline);
return drawing;
I think in OpenXML there is a property highlight text color. How do I get that in C# code?
Actually you don't set the alignment of drawing directly. You place it in paragraph for example and set its property alignment.
this is the code I'm using:
public void AddImageParagraph(Drawing element, JustificationValues alignment = JustificationValues.Left)
{
Paragraph paragraph = new Paragraph();
ParagraphProperties paragraphProperties = new ParagraphProperties();
Justification justification = new Justification()
{
Val = alignment
};
paragraphProperties.Append(justification);
Run run = new Run(element);
paragraph.Append(run);
paragraph.Append(paragraphProperties);
mBody.Append(paragraph);
}

Categories

Resources