chart.DrawToBitmap blank - c#

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

Related

C# Saving Live Chart to PNG in WinForms

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!

Add text from QR Code next to generated PNG

I have made an application which generates me a QR Code in a PNG image, but now I have to insert the text from QR Code next to the QR Code image.
I don't have any experience using ZXing Library but I'm thinking that it may contain an option for this...
Example:
Code:
namespace QR_Code_with_WFA
{
public void CreateQRImage(string inputData)
{
if (inputData.Trim() == String.Empty)
{
System.Windows.Forms.MessageBox.Show("Data must not be empty.");
}
BarcodeWriter qrcoder = new ZXing.BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions
{
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H,
Height = 250,
Width = 250
}
};
string tempFileName = System.IO.Path.GetTempPath() + inputData + ".png";
Image image;
String data = inputData;
var result = qrcoder.Write(inputData);
image = new Bitmap(result);
image.Save(tempFileName);
System.Diagnostics.Process.Start(tempFileName);
}
}
Well, ZXing.BarcodeWriter.Options has property PureBarcode, which will put source text into generated image when set to false.
Unfortunately it has no effect when format of barcode is BarcodeFormat.QR_CODE (and it is by design).
But you can draw your text manually after you've generated barcode image:
var result = qrcoder.Write(inputData);
using (var g = Graphics.FromImage(result))
using (var font = new Font(FontFamily.GenericMonospace, 12))
using (var brush = new SolidBrush(Color.Black))
using(var format = new StringFormat(){Alignment = StringAlignment.Center})
{
int margin = 5, textHeight = 20;
var rect = new RectangleF(margin, result.Height - textHeight,
result.Width - 2 * margin, textHeight);
g.DrawString(inputData, font, brush, rect, format);
}
result.Save(tempFileName);
Note you can select your own font size and fontfamily which will better suite your goals.
Update:
In the case you're trying to place text to the right from image - you have to "extend" to the right your generated image first, and then draw text:
var result = qrcoder.Write(inputData);
int textWidth = 200, textHeight = 20;
// creating new bitmap having imcreased width
var img = new Bitmap(result.Width + textWidth, result.Height);
using (var g = Graphics.FromImage(img))
using (var font = new Font(FontFamily.GenericMonospace, 12))
using (var brush = new SolidBrush(Color.Black))
using (var bgBrush = new SolidBrush(Color.White))
using (var format = new StringFormat() { Alignment = StringAlignment.Near })
{
// filling background with white color
g.FillRectangle(bgBrush, 0, 0, img.Width, img.Height);
// drawing your generated image over new one
g.DrawImage(result, new Point(0,0));
// drawing text
g.DrawString(inputData, font, brush, result.Width, (result.Height - textHeight) / 2, format);
}
img.Save(tempFileName);

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?

Getting SharpDX.Direct2D1.Bitmap from Texture2D

I'm trying to create an off-screen bitmap to draw on it and to draw it with Direct2D1.RenderTarget.DrawBitmap then. So I create Texture2D and get the Bitmap from it. But I receive the error
[D2DERR_UNSUPPORTED_PIXEL_FORMAT/UnsupportedPixelFormat]
in last string of code. Please help me to understand, what have i done wrong here?
m_texture = new Texture2D(
context.Device,
new Texture2DDescription() {
ArraySize = 1,
BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.B8G8R8A8_UNorm,
Height = bitmapSize.Height,
Width = bitmapSize.Width,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SampleDescription() {
Count = 1,
Quality = 0
},
Usage = ResourceUsage.Default
}
);
m_surface = m_texture.QueryInterface<Surface>();
using (SharpDX.Direct2D1.Factory factory = new SharpDX.Direct2D1.Factory()) {
m_renderTarget = new RenderTarget(
factory,
m_surface,
new RenderTargetProperties() {
DpiX = 0.0f, // default dpi
DpiY = 0.0f, // default dpi
MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT,
Type = RenderTargetType.Hardware,
Usage = RenderTargetUsage.None,
PixelFormat = new SharpDX.Direct2D1.PixelFormat(
Format.Unknown,
AlphaMode.Premultiplied
)
}
);
}
m_bitmap = new SharpDX.Direct2D1.Bitmap(m_renderTarget, m_surface);
public static SharpDX.Direct2D1.Bitmap GetBitmapFromSRV(SharpDX.Direct3D11.ShaderResourceView srv, RenderTarget renderTarger)
{
using (var texture = srv.ResourceAs<Texture2D>())
using (var surface = texture.QueryInterface<Surface>())
{
var bitmap = new SharpDX.Direct2D1.Bitmap(renderTarger, surface, new SharpDX.Direct2D1.BitmapProperties(new SharpDX.Direct2D1.PixelFormat(
Format.R8G8B8A8_UNorm,
SharpDX.Direct2D1.AlphaMode.Premultiplied)));
return bitmap;
}
}

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