public void HeatMapTest() { HeatMapModel heatMap = HeatMapModel.CreateRandom(10, 10, 0, 100); folderResults.SaveText(heatMap.GetDataTable("HeatMap_Random", "").textTable(4), "HeatMapData.txt", imbSCI.Data.enums.getWritableFileMode.overwrite, "Values from random heat map"); HeatMapRender heatMapRender = new HeatMapRender(); Svg.SvgDocument svg = heatMapRender.RenderAndSave(heatMap, folderResults.pathFor("heatmap_render.svg", imbSCI.Data.enums.getWritableFileMode.overwrite)); var jpg = folderResults.pathFor("heatmap_render.jpg", imbSCI.Data.enums.getWritableFileMode.overwrite); svg.SaveJPEG(jpg); heatMapRender = new HeatMapRender(); heatMapRender.style.LowColor = Color.Blue; heatMapRender.style.HighColor = Color.Red; Svg.SvgDocument svgbr = heatMapRender.RenderAndSave(heatMap, folderResults.pathFor("heatmap_render_bluered.svg", imbSCI.Data.enums.getWritableFileMode.overwrite)); jpg = folderResults.pathFor("heatmap_render_bluered.jpg", imbSCI.Data.enums.getWritableFileMode.overwrite); svgbr.SaveJPEG(jpg); }
public static BitmapSource GetBitmapSource(Stream Source, float overAllSize = 256.0f) { Svg.SvgDocument doc = Svg.SvgDocument.Open <Svg.SvgDocument>(Source); float w = doc.GetDimensions().Width; float h = doc.GetDimensions().Height; float ratioX = overAllSize / w; float ratioY = overAllSize / h; float ratio = ratioX < ratioY ? ratioX : ratioY; int newHeight = Convert.ToInt32(h * ratio); int newWidth = Convert.ToInt32(w * ratio); if (doc.Width.Type != Svg.SvgUnitType.Percentage && doc.Height.Type != Svg.SvgUnitType.Percentage) { doc.Transforms.Add(new Svg.Transforms.SvgScale(ratio)); } Bitmap HBITMAP = doc.Draw(newWidth, newHeight); BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(HBITMAP.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return(bs); }
/* * corner-always-threshold <angle-in-degrees>: if the angle at a pixel is less than this, it is considered a corner, even if it is within `corner-surround' pixels of another corner; default is 60. * corner-surround <unsigned>: number of pixels on either side of a point to consider when determining if that point is a corner; default is 4. * corner-threshold <angle-in-degrees>: if a pixel, its predecessor(s), and its successor(s) meet at an angle smaller than this, it's a corner; default is 100. * despeckle-level <unsigned>: 0..20; default is no despeckling. * despeckle-tightness <real>: 0.0..8.0; default is 2.0. * imageerror-threshold <real>: subdivide fitted curves that are off by more pixels than this; default is 2.0. * filter-iterations <unsigned>: smooth the curve this many times before fitting; default is 4. * line-reversion-threshold <real>: if a spline is closer to a straight line than this, weighted by the square of the curve length, keep it a straight line even if it is a list with curves; default is .01. * line-threshold <real>: if the spline is not more than this far away from the straight line defined by its endpoints, then output a straight line; default is 1. * preserve-width: whether to preserve line width prior to thinning. * remove-adjacent-corners: remove corners that are adjacent. * tangent-surround <unsigned>: number of points on either side of a point to consider when computing the tangent at that point; default is 3. */ //System.Text.RegularExpressions.Regex colorRegex = new System.Text.RegularExpressions.Regex("stroke:#([0-9a-fA-F]+);", System.Text.RegularExpressions.RegexOptions.Compiled); private void PreviewCenterline(Bitmap bmp) { try { if (MustExitTH) { return; } Svg.SvgDocument svg = Autotrace.BitmapToSvgDocument(bmp, UseCornerThreshold, CornerThreshold, UseLineThreshold, LineThreshold); if (MustExitTH) { return; } using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), g.ClipBounds); if (MustExitTH) { return; } GraphicsPath path = new GraphicsPath(); svg.Draw(path); g.SmoothingMode = SmoothingMode.HighQuality; g.DrawPath(Pens.Red, path); } } catch (Exception ex) { using (Graphics g = Graphics.FromImage(bmp)) { if (MustExitTH) { return; } g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), g.ClipBounds); if (MustExitTH) { return; } StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Center; format.Alignment = StringAlignment.Center; g.DrawString(ex.Message, SystemFonts.DefaultFont, Brushes.Red, new RectangleF(0, 0, bmp.Width, bmp.Height), format); if (MustExitTH) { return; } } } }
private void CreatePreview(string filename) { string fcontent = System.IO.File.ReadAllText(filename); Svg.SvgDocument svg = Svg.SvgDocument.FromSvg <Svg.SvgDocument>(fcontent); svg.Ppi = 600; PbImage.Image = svg.Draw(); PbVector.Image = svg.Draw(true); }
/// <summary> /// Convert a svg file loaded to an image base64 (PNG) /// </summary> /// <param name="data"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static string GetSvgBase64(byte[] data, int width, int height) { using (MemoryStream stream = new MemoryStream(data)) { Svg.SvgDocument image = Svg.SvgDocument.Open <Svg.SvgDocument>(stream); Bitmap bitmap = new Bitmap(image.Draw(), width, height); MemoryStream newStream = new MemoryStream(); bitmap.Save(newStream, System.Drawing.Imaging.ImageFormat.Png); return(Convert.ToBase64String(newStream.ToArray())); } }
internal System.Drawing.Image GetGdiImage(IconCollectionInfo collectionInfo, IconFileInfo fileInfo) { string iconFileKey = GetIconFileKey(collectionInfo, fileInfo); System.Drawing.Image result = null; if (!m_gdiImages.TryGetValue(iconFileKey, out result)) { // Try to load the icon from svg file var svgIconLink = TryFindSvgIcon(collectionInfo, fileInfo); if (svgIconLink != null) { Stopwatch sw = new Stopwatch(); sw.Start(); using (Stream inStream = svgIconLink.OpenRead()) { Svg.SvgDocument svgDoc = Svg.SvgDocument.Open <Svg.SvgDocument>(inStream); System.Drawing.Bitmap targetBitmap = new System.Drawing.Bitmap(collectionInfo.IconSideWidthPixel, collectionInfo.IconSideWidthPixel); using (CustomSvgRenderer svgRenderer = new CustomSvgRenderer(targetBitmap, Color.FromArgb(collectionInfo.IconForeColor))) { svgDoc.Overflow = Svg.SvgOverflow.Auto; svgRenderer.SetBoundable(new GenericBoundable(0f, 0f, (float)targetBitmap.Width, (float)targetBitmap.Height)); SizeF dimensions = svgDoc.GetDimensions(); svgRenderer.ScaleTransform((float)targetBitmap.Width / dimensions.Width, (float)targetBitmap.Height / dimensions.Height, MatrixOrder.Append); svgDoc.Draw(svgRenderer); } result = targetBitmap; } sw.Stop(); } // Try to load the icon from png file if (result == null) { var pngIconLink = TryFindPngIcon(collectionInfo, fileInfo); if (pngIconLink != null) { using (Stream inStream = pngIconLink.OpenRead()) { result = System.Drawing.Bitmap.FromStream(inStream); } } } m_gdiImages[iconFileKey] = result; } return(result); }
static void Main(string[] args) { XmlDocument document = new XmlDocument(); OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "|*.svg"; openFile.ShowDialog(); document.Load(openFile.FileName); Svg.SvgDocument svg = Svg.SvgDocument.Open(document); var bmp = svg.Draw(); bmp.Save(openFile.FileName + ".png", System.Drawing.Imaging.ImageFormat.Png); }
private void defaultSizeButton_Click(object sender, EventArgs e) { Svg.SvgDocument svgDocument = Svg.SvgDocument.Open(path); int width = Convert.ToInt32(svgDocument.Width.Value); int height = Convert.ToInt32(svgDocument.Height.Value); bool aspectChecked = aspectRatioCheckbox.Checked; widthNumeric.Value = width; heightNumeric.Value = height; aspectRatioCheckbox.Checked = aspectChecked; }
private Bitmap SvgToBitmap(List <byte[]> svgList, int width, int height) { var doc = new Svg.SvgDocument(); foreach (var svg in svgList) { using (var svgStream = new MemoryStream(svg)) { var svgChild = Svg.SvgDocument.Open <Svg.SvgDocument>(svgStream); doc.Children.Add(svgChild); } } return(doc.Draw(width, height)); }
private void ImageListBoxControl_SelectedIndexChanged(object sender, EventArgs e) { try { string newName = Path.GetExtension(imageListBoxControl.SelectedItem.ToString()); if (newName.EndsWith(".svg")) { SVGSample.svg.SVGParser.MaximumSize = new Size(1000, 700); Svg.SvgDocument svgDocument = SVGSample.svg.SVGParser.GetSvgDocument(imageListBoxControl.SelectedItem.ToString()); Bitmap bitmap = SVGSample.svg.SVGParser.GetBitmapFromSVG(imageListBoxControl.SelectedItem.ToString()); Pic.Image = bitmap; } else { Pic.Image = Image.FromFile(imageListBoxControl.SelectedItem.ToString()); } } catch (Exception) { } }
public static Sprite GetSpriteFromSVG(string fileName) { int index = TextureFileNames.IndexOf(fileName); if (index >= 0) { // Texture Already Exists // move it to the end of the array and return it Texture texture = Textures[index]; string name = TextureFileNames[index]; Textures.RemoveAt(index); TextureFileNames.RemoveAt(index); Textures.Add(texture); TextureFileNames.Add(name); return(new Sprite(Textures[Textures.Count - 1])); } else { // New Texture (from .svg) try { Svg.SvgDocument svg = Svg.SvgDocument.Open(fileName); System.Drawing.Bitmap bitmap = svg.Draw(); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Texture texture = new Texture(stream); Textures.Add(texture); TextureFileNames.Add(fileName); return(new Sprite(new Texture(texture))); } } catch (Exception) { } } return(null); }
internal static byte[] convertToImage(string svg) // $TO-DO: chane to "internal" after unit-testing { byte[] result = Array.Empty <byte>(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); try { xmlDoc.LoadXml(svg); Svg.SvgDocument svgDoc = Svg.SvgDocument.Open(xmlDoc); System.Drawing.Bitmap img = svgDoc.Draw(); System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter(); result = (byte[])converter.ConvertTo(img, typeof(byte[])); } catch { return(result); } return(result); }
private void btnAutoRefresh_Click(object sender, EventArgs e) { if (btnAutoRefresh.Text == "自动刷新") { //开始启动自动刷新 string svgName = helper.GetSvgPath(Convert.ToInt32(this.cbTopology.SelectedValue), mysqlConnectionString); if (svgName == "error") { return; } m_ImagePath = m_ImageBasePath + svgName; CollectionData.Util.SVGParser.MaximumSize = new Size(this.picView.Width, this.picView.Height); m_SvgDocument = CollectionData.Util.SVGParser.GetSvgDocument(m_ImagePath); //1. 加载页面 LoadData(); //2. 启动自动刷新定时器 this.timerTopology.Enabled = true; //3. 修改名称为"手动刷新" this.btnAutoRefresh.Text = "停止刷新"; } else { //开始启动自动刷新 //1. 停止自动刷新定时器 this.timerTopology.Enabled = false; //2. 修改名称为"自动刷新" this.btnAutoRefresh.Text = "自动刷新"; } }
/* * corner-always-threshold <angle-in-degrees>: if the angle at a pixel is less than this, it is considered a corner, even if it is within `corner-surround' pixels of another corner; default is 60. * corner-surround <unsigned>: number of pixels on either side of a point to consider when determining if that point is a corner; default is 4. * corner-threshold <angle-in-degrees>: if a pixel, its predecessor(s), and its successor(s) meet at an angle smaller than this, it's a corner; default is 100. * despeckle-level <unsigned>: 0..20; default is no despeckling. * despeckle-tightness <real>: 0.0..8.0; default is 2.0. * imageerror-threshold <real>: subdivide fitted curves that are off by more pixels than this; default is 2.0. * filter-iterations <unsigned>: smooth the curve this many times before fitting; default is 4. * line-reversion-threshold <real>: if a spline is closer to a straight line than this, weighted by the square of the curve length, keep it a straight line even if it is a list with curves; default is .01. * line-threshold <real>: if the spline is not more than this far away from the straight line defined by its endpoints, then output a straight line; default is 1. * preserve-width: whether to preserve line width prior to thinning. * remove-adjacent-corners: remove corners that are adjacent. * tangent-surround <unsigned>: number of points on either side of a point to consider when computing the tangent at that point; default is 3. */ //System.Text.RegularExpressions.Regex colorRegex = new System.Text.RegularExpressions.Regex("stroke:#([0-9a-fA-F]+);", System.Text.RegularExpressions.RegexOptions.Compiled); private void PreviewCenterline(Bitmap bmp) { Svg.SvgDocument svg = Autotrace.BitmapToSvgDocument(bmp, UseCornerThreshold, CornerThreshold, UseLineThreshold, LineThreshold); if (MustExitTH) { return; } using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(new SolidBrush(Color.FromArgb(180, Color.White)), g.ClipBounds); if (MustExitTH) { return; } GraphicsPath path = new GraphicsPath(); svg.Draw(path); g.SmoothingMode = SmoothingMode.HighQuality; g.DrawPath(Pens.Red, path); } }
private IList <IBaseShape> Convert(Svg.SvgDocument document, out double width, out double height) { var picture = SKSvg.ToModel(document); if (picture == null) { width = double.NaN; height = double.NaN; return(null); } var shapes = new List <IBaseShape>(); var factory = _serviceProvider.GetService <IFactory>(); ToShape(picture, shapes, factory); var group = factory.CreateGroupShape("svg"); group.Shapes = group.Shapes.AddRange(shapes); width = picture.CullRect.Width; height = picture.CullRect.Height; return(Enumerable.Repeat <IBaseShape>(group, 1).ToList()); }
public static System.Drawing.Bitmap create(IList <double> XValues, IList <double> YValues, List <object> chartOptions = null) { //sanitize the incoming data if (XValues.Count() <= 0 || YValues.Count() <= 0) { throw new ArgumentException("The inputs need to be at least 1 item."); } if (XValues.GetType() != typeof(double[]) || YValues.GetType() != typeof(double[])) { throw new ArgumentException("Currently only numbers are supported on X and Y values, sorry!"); } if (XValues.Count() != YValues.Count()) { throw new ArgumentException("The values of X and Y are not of same count. Not currently supported, sorry!"); } string chartTitle; string XLabel; string YLabel; double chartAreaWidth; double chartAreaHeight; int LineOrAreaFlag; double plotRadius; double opacity; int interactiveOption; int saveAsSVGOption; string saveLocation; //read all options here if (chartOptions.Count == 11) { chartTitle = chartOptions[0].ToString(); XLabel = chartOptions[1].ToString(); YLabel = chartOptions[2].ToString(); chartAreaWidth = Convert.ToDouble(chartOptions[3]); chartAreaHeight = Convert.ToDouble(chartOptions[4]); LineOrAreaFlag = Convert.ToInt32(chartOptions[5]); plotRadius = Convert.ToDouble(chartOptions[6]); opacity = Convert.ToDouble(chartOptions[7]); interactiveOption = Convert.ToInt32(chartOptions[8]); saveAsSVGOption = Convert.ToInt32(chartOptions[9]); saveLocation = chartOptions[10].ToString(); } else { chartTitle = "Chart title"; XLabel = "X Values"; YLabel = "Y Values"; chartAreaWidth = 500; chartAreaHeight = 500; LineOrAreaFlag = 0; plotRadius = 2.0; opacity = 50; interactiveOption = 0; saveAsSVGOption = 0; saveLocation = "Desktop"; } if (saveLocation == "" || string.Compare(saveLocation, "Desktop") == 0 || saveLocation == null) { saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } opacity = (opacity <= 0.0) ? 0.01 : opacity / 100; opacity = (opacity >= 1.0) ? 1.0 : opacity; //get all the axis values for X and Y axis var xAxisVals = findAxis(XValues); var yAxisVals = findAxis(YValues); double maxX = XValues.Max(); double minX = XValues.Min(); double maxY = YValues.Max(); double minY = YValues.Min(); var chartMargin = 50; var chartWid = chartAreaWidth + chartMargin; var chartHei = chartAreaHeight + chartMargin; var minPosX = chartMargin; var minPosY = chartMargin; var maxPosX = chartWid - chartMargin; var maxPosY = chartHei - chartMargin; var SVGStringBuilder = new StringBuilder(); SVGStringBuilder.Append("<?xml version='1.0' encoding='UTF-8'?>"); SVGStringBuilder.Append(String.Format("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='{0}px' height='{1}px' viewBox='0 0 {2} {3}' xml:space='preserve' >\n", chartWid, chartHei, chartWid, chartHei)); //draw graph background. The plot is always 500pt by 500pt SVGStringBuilder.Append(String.Format("<rect x='0' y='0' width='{0}' height='{1}' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n", chartWid, chartHei)); //draw axis and marking SVGStringBuilder.Append("<g name='xaxis'> \n"); for (int i = 0; i < xAxisVals.Count; ++i) { var x = minPosX + (maxPosX - minPosX) * i / (xAxisVals.Count - 1); SVGStringBuilder.Append(String.Format("<path d='M {0} {1} L {2} {3}' style='stroke-width:1px; stroke: #DDD; fill: none; shape-rendering: crispEdges;'/>\n", x, chartMargin, x, (chartHei - chartMargin))); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px;' text-anchor='middle'>{2}</text>", x, (chartHei - chartMargin + 15), xAxisVals[i])); } SVGStringBuilder.Append("</g> \n"); SVGStringBuilder.Append("<g name='yaxis'> \n"); for (int i = 0; i < yAxisVals.Count; ++i) { var y = minPosY + (maxPosY - minPosY) * i / (yAxisVals.Count - 1); SVGStringBuilder.Append(String.Format("<path d='M{0} {1} L{2} {3}' style='stroke-width:1px; stroke: #DDD; fill: none; shape-rendering: crispEdges;'/>\n", chartMargin, y, (chartWid - chartMargin), y)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px; ' text-anchor='middle' transform='rotate(270 {2},{3})'>{4}</text>", (chartMargin - 10), y, (chartMargin - 10), y, (yAxisVals[yAxisVals.Count - i - 1]))); } SVGStringBuilder.Append("</g> \n"); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='{2}' height='{3}' style='stroke-width:1px; stroke: #AAA; fill: none; shape-rendering: crispEdges;' />\n", chartMargin, chartMargin, (chartWid - 2 * chartMargin), (chartHei - 2 * chartMargin))); //draw labels and title along axis SVGStringBuilder.Append(String.Format("<g>")); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' font-size='12px' fill='#222' text-anchor='middle' font-family='sans-serif' >{2}</text>", (chartWid / 2), (30), chartTitle)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' font-size='12px' fill='#222' text-anchor='middle' font-family='sans-serif' >{2}</text>", (chartWid / 2), (chartHei - 15), XLabel)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' font-size='12px' fill='#222' text-anchor='middle' font-family='sans-serif' transform='rotate(270 {2},{3})'>{4}</text>", (chartMargin / 2), (chartHei / 2), (chartMargin / 2), (chartHei / 2), YLabel)); SVGStringBuilder.Append(String.Format("</g>")); StringBuilder tempSVGStringBuilder = new StringBuilder(); var circleColor = "#C81E1E"; //draw the points on the graph if (LineOrAreaFlag == 1) { circleColor = "rgba(0, 0, 0, 0)"; tempSVGStringBuilder.Append("<path id='linePlot' d='"); } if (LineOrAreaFlag == 2) { circleColor = "rgba(0, 0, 0, 0)"; tempSVGStringBuilder.Append("<path id='linePlot' d='"); } SVGStringBuilder.Append(String.Format("<g>", circleColor)); for (int i = 0; i < XValues.Count; ++i) { var posX = (minPosX * (XValues[i] - xAxisVals[xAxisVals.Count - 1]) + maxPosX * (xAxisVals[0] - XValues[i])) / (xAxisVals[0] - xAxisVals[xAxisVals.Count - 1]); var posY = (minPosY * (YValues[i] - yAxisVals[yAxisVals.Count - 1]) + maxPosY * (yAxisVals[0] - YValues[i])) / (yAxisVals[0] - yAxisVals[yAxisVals.Count - 1]); if (i == 0 && LineOrAreaFlag == 1) { tempSVGStringBuilder.Append(String.Format("M {0},{1} ", posX, (chartHei - posY))); } else if (i == 0 && LineOrAreaFlag == 2) { tempSVGStringBuilder.Append(String.Format("M {0},{1} L {2},{3} ", posX, (chartHei - chartMargin), posX, (chartHei - posY))); } else { tempSVGStringBuilder.Append(String.Format("L {0},{1} ", posX, (chartHei - posY))); } if (i == XValues.Count - 1 && LineOrAreaFlag == 2) { tempSVGStringBuilder.Append(String.Format("L {0},{1} ", posX, (chartHei - chartMargin))); } SVGStringBuilder.Append(String.Format("<circle class='sp' id='sp{0}' cx='{1}' cy='{2}' r='{3}' fill='{4}' style='fill-opacity:{5};'/>", i, posX, (chartHei - posY), plotRadius, circleColor, opacity)); if (interactiveOption == 1) { SVGStringBuilder.Append(String.Format("<text id='tt' x='{0}' y='{1}' visibility='hidden' fill='#000' font-family='sans-serif' font-size='12' >({2},{3})", (posX + 20), (chartHei - posY + 20), XValues[i], YValues[i])); SVGStringBuilder.Append(String.Format("<set attributeName='visibility' from='hidden' to='visible' begin='sp{0}.mouseover' end='sp{1}.mouseout'/>", i, i)); SVGStringBuilder.Append("</text>"); } } if (LineOrAreaFlag == 1) { tempSVGStringBuilder.Append("' style='stroke-width:2px; stroke: rgba(200, 30, 30, 0.7); fill:none; ' />"); } else if (LineOrAreaFlag == 2) { tempSVGStringBuilder.Append("' style='stroke-width:0; stroke: rgba(200, 30, 30, 0.7); fill:rgba(200, 30, 30, 0.5); ' />"); } SVGStringBuilder.Append(tempSVGStringBuilder.ToString()); SVGStringBuilder.Append("</g>"); //SVGStringBuilder.Append("<defs><style type='text/css'><![CDATA[ .sp:hover { stroke: rgba(200, 30, 30, 1); stroke-width:1px; } ]]></style></defs>"); SVGStringBuilder.Append("</svg>"); var SVGContent = SVGStringBuilder.ToString(); if (saveAsSVGOption != 0) { var file = CreateNewSVGFile(saveLocation, "scatterPlot"); file.WriteLine(SVGContent); file.Close(); } XmlDocument doc = new XmlDocument(); doc.LoadXml(SVGContent); Svg.SvgDocument svgdoc = new Svg.SvgDocument(); var xmlStream = new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(doc.InnerXml)); svgdoc = Svg.SvgDocument.Open(xmlStream); var imageStream = new System.IO.MemoryStream(); svgdoc.Draw().Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp); System.Drawing.Bitmap imageFile = new System.Drawing.Bitmap(imageStream); return(imageFile); }
public static System.Drawing.Bitmap create(IList <double> values, List <object> chartOptions = null) { //sanitize the incoming data if (values.Count() <= 0) { throw new ArgumentException("The inputs need to be at least 1 item."); } if (values.GetType() != typeof(double[])) { throw new ArgumentException("Currently only numbers are supported, sorry!"); } string chartTitle; string XLabel; string yLabel = "Occurance count"; int intervals; double minValuePlot; double maxValuePlot; int chartAreaWidth; int chartAreaHeight; double opacity; int interactiveOption; int saveAsSVGOption; string saveLocation; if (chartOptions.Count == 12) { chartTitle = chartOptions[0].ToString(); XLabel = chartOptions[1].ToString(); yLabel = chartOptions[2].ToString(); intervals = Convert.ToInt32(chartOptions[3]); minValuePlot = Convert.ToDouble(chartOptions[4]); maxValuePlot = Convert.ToDouble(chartOptions[5]); chartAreaWidth = Convert.ToInt32(chartOptions[6]); chartAreaHeight = Convert.ToInt32(chartOptions[7]); opacity = Convert.ToDouble(chartOptions[8]); interactiveOption = Convert.ToInt32(chartOptions[9]); saveAsSVGOption = Convert.ToInt32(chartOptions[10]); saveLocation = chartOptions[11].ToString(); } else { chartTitle = "Chart title"; XLabel = "Values"; yLabel = "Occurances count"; intervals = 10; minValuePlot = -1; maxValuePlot = -1; chartAreaWidth = 500; chartAreaHeight = 500; opacity = 50.0; interactiveOption = 0; saveAsSVGOption = 0; saveLocation = "Desktop"; } if (minValuePlot == -1 && maxValuePlot == -1) { minValuePlot = values.Min(); maxValuePlot = values.Max(); } //make sure the minVal is smaller than the mininum and maxVal is greater than maximium - so that the plot is not cut off if (minValuePlot > values.Min()) { throw new ArgumentException("The minValuePlot needs to be smaller than the minumum inside the values list", "minValuePlot"); } if (maxValuePlot < values.Max()) { throw new ArgumentException("The maxValuePlot needs to be bigger than the maximum inside the values list", "maxValuePlot"); } if (saveLocation == "" || string.Compare(saveLocation, "Desktop") == 0 || saveLocation == null) { saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } var chartWid = chartAreaWidth; var chartHei = chartAreaHeight; var chartMargin = 50; chartWid = chartWid + chartMargin; chartHei = chartHei + chartMargin; var minPosX = chartMargin + 20; var minPosY = chartMargin; var maxPosX = chartWid - chartMargin - 20; var maxPosY = chartHei - chartMargin; var diff = (maxValuePlot - minValuePlot) / intervals; List <double> axisVals = new List <double>(); for (int i = 0; i <= intervals; ++i) { axisVals.Add(minValuePlot + i * diff); } //draw the xAxis marking var SVGStringBuilder = new StringBuilder(); SVGStringBuilder.Append(String.Format("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='{0}px' height='{1}px' viewBox='0 0 {0} {1}' xml:space='preserve' >\n", chartWid, chartHei)); //draw graph background. The plot is always 500pt by 500pt SVGStringBuilder.Append(String.Format("<rect x='0' y='0' width='{0}' height='{1}' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n", chartWid, chartHei)); List <int> histogram = new List <int>(new int[intervals]); for (int i = 0; i < intervals; ++i) { histogram[i] = 0; } //find the histogram values foreach (double val in values) { //var intervalNumber = 0; for (int i = 0; i < intervals; ++i) { if (val < axisVals[i + 1] && val >= axisVals[i]) { histogram[i] = histogram[i] + 1; break; } if (val == values.Max()) { histogram[intervals - 1] += 1; break; } } } //the y axis will always start from 0 to the max of the numbers var yAxisVals = findAxis(histogram); SVGStringBuilder.Append("<g name='yaxis'> \n"); for (int i = 0; i < yAxisVals.Count; ++i) { var x = minPosY + (maxPosY - minPosY) * i / (yAxisVals.Count - 1); SVGStringBuilder.Append(String.Format("<path d='M{0} {1} L{2} {1}' style='stroke-width:1px; stroke: #DDD; fill: none; shape-rendering: crispEdges;'/> \n", chartMargin, x, (chartWid - chartMargin))); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px; ' text-anchor='middle' transform='rotate(270 {0},{1})'>{2}</text>", (chartMargin - 10), x, yAxisVals[yAxisVals.Count - i - 1])); } SVGStringBuilder.Append("</g> \n"); SVGStringBuilder.Append("<g name='xaxis'> \n"); for (int i = 0; i < axisVals.Count; ++i) { var x = minPosX + (maxPosX - minPosX) * i / (axisVals.Count - 1); SVGStringBuilder.Append(String.Format("<path d='M{0} {1} L{0} {2}' style='stroke-width:1px; stroke: #AAA; fill: none; shape-rendering: crispEdges;'/> \n", x, (chartHei - chartMargin - 7), (chartHei - chartMargin + 7))); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px;' text-anchor='middle'>{2}</text>", x, (chartHei - chartMargin + 15), axisVals[i])); } SVGStringBuilder.Append("</g> \n"); //draw the rectangles SVGStringBuilder.Append("<g name='yaxis'> \n"); for (int i = 0; i < histogram.Count; ++i) { var x = minPosX + (maxPosX - minPosX) * i / (histogram.Count); var y = (minPosY * (histogram[i] - yAxisVals[yAxisVals.Count - 1]) + maxPosY * (yAxisVals[0] - histogram[i])) / (yAxisVals[0] - yAxisVals[yAxisVals.Count - 1]); SVGStringBuilder.Append(String.Format("<rect id='histogramBar{0}' x='{1}' y='{2}' width='{3}' height='{4}' style='stroke-width:1px; stroke: #FFFFFF; fill: #C81E1E; shape-rendering: crispEdges; fill-opacity:{5};' /> \n", i, x, (chartHei - y), ((maxPosX - minPosX) / (histogram.Count)), (y - chartMargin), (opacity / 100.0))); if (interactiveOption == 1) { SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' visibility='hidden' fill='#4192d9' font-family='sans-serif' font-size='12' text-anchor='middle'> {2}<text/>", (x + ((maxPosX - minPosX) / (histogram.Count)) / 2), (chartHei - y - 10), histogram[i])); SVGStringBuilder.Append(String.Format("<set attributeName='visibility' from='hidden' to='visible' begin='histogramBar{0}.mouseover' end='histogramBar{0}.mouseout'/>", i)); SVGStringBuilder.Append("</text>"); } } SVGStringBuilder.Append("</g> \n"); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{0}' width='{1}' height='{2}' style='stroke-width:1px; stroke: #AAA; fill: none; shape-rendering: crispEdges;' />\n", chartMargin, (chartWid - 2 * chartMargin), (chartHei - 2 * chartMargin))); if (chartTitle == "") { chartTitle = "Histogram of " + XLabel; } //draw values along axis SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#222; font-family: sans-serif; font-size: 12px;' text-anchor='middle'>{2}</text>", (chartWid / 2), 30, chartTitle)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#444; font-family: sans-serif; font-size: 10px;' text-anchor='middle'>{2}</text>", (chartWid / 2), (chartHei - 15), XLabel)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#444; font-family: sans-serif; font-size: 10px;' transform='rotate(270 {0},{1})' text-anchor='middle'>{2}</text>", (chartMargin / 2), (chartHei / 2), yLabel)); //close the svg SVGStringBuilder.Append("</svg>"); var SVGContent = SVGStringBuilder.ToString(); if (saveAsSVGOption != 0) { var file = CreateNewSVGFile(saveLocation, "histogramPlot"); file.WriteLine(SVGContent); file.Close(); } XmlDocument doc = new XmlDocument(); doc.LoadXml(SVGContent); Svg.SvgDocument svgdoc = new Svg.SvgDocument(); var xmlStream = new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(doc.InnerXml)); svgdoc = Svg.SvgDocument.Open(xmlStream); var imageStream = new System.IO.MemoryStream(); svgdoc.Draw().Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp); System.Drawing.Bitmap imageFile = new System.Drawing.Bitmap(imageStream); return(imageFile); }
public static System.Drawing.Bitmap createLinear(double valueToMonitor, List <object> chartOptions = null) { //sanitize the incoming data if (valueToMonitor.GetType() != typeof(double)) { throw new ArgumentException("The value to monitor is not valid, sorry!"); } string label; double minValue; double maxValue; int chartWidth; int saveAsSVGOption; string saveLocation; //read all options here if (chartOptions.Count == 6) { label = chartOptions[0].ToString(); minValue = Convert.ToDouble(chartOptions[1]); maxValue = Convert.ToDouble(chartOptions[2]); chartWidth = Convert.ToInt32(chartOptions[3]); saveAsSVGOption = Convert.ToInt32(chartOptions[4]); saveLocation = chartOptions[5].ToString(); } else { label = "Label"; minValue = 0; maxValue = 100; chartWidth = 500; saveAsSVGOption = 1; saveLocation = "Desktop"; } if (minValue >= maxValue) { throw new ArgumentException("Minimum value needs to be smaller than the maximum value."); } if (chartWidth < 500) { chartWidth = 500; } if (saveLocation == "" || string.Compare(saveLocation, "Desktop") == 0 || saveLocation == null) { saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } var progressHeight = 20; var chartMargin = 50; var chartWid = chartWidth + 2 * chartMargin + 2 * progressHeight; var chartHei = progressHeight + 2 * chartMargin; var SVGStringBuilder = new StringBuilder(); SVGStringBuilder.Append("<?xml version='1.0' encoding='UTF-8'?>"); SVGStringBuilder.Append(String.Format("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='{0}px' height='{1}px' viewBox='0 0 {2} {3}' xml:space='preserve' >\n", chartWid, chartHei, chartWid, chartHei)); //draw graph background. The plot is always 500pt by 500pt SVGStringBuilder.Append(String.Format("<rect x='0' y='0' width='{0}' height='{1}' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n", chartWid, chartHei)); var progressWidth = (chartWidth * valueToMonitor - minValue * chartWidth) / (maxValue - minValue); if (progressWidth < 0) { progressWidth = 0; } if (progressWidth > chartWidth) { progressWidth = chartWidth; } var minFillColor = "none"; var maxFillColor = minFillColor; if (valueToMonitor < minValue) { minFillColor = "rgba(214, 63, 41, 1)"; } if (valueToMonitor > maxValue) { maxFillColor = "rgba(214, 63, 41, 1)"; } //draw marking SVGStringBuilder.Append("<g name='skeleton'> \n"); //draw rectangles SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='{2}' height='{3}' style='fill:#3498DB; shape-rendering: crispEdges;' />\n", chartMargin + progressHeight, chartMargin, progressWidth, progressHeight)); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='{2}' height='{2}' style='fill:{3}; stroke-width:1px; stroke: #888; shape-rendering: crispEdges;' />\n", chartMargin, chartMargin, progressHeight, minFillColor)); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='{2}' height='{3}' style='fill:none; stroke-width:1px; stroke: #888; shape-rendering: crispEdges;' />\n", chartMargin + progressHeight, chartMargin, chartWidth, progressHeight)); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='{2}' height='{2}' style='fill:{3}; stroke-width:1px; stroke: #888; shape-rendering: crispEdges;' />\n", chartMargin + progressHeight + chartWidth, chartMargin, progressHeight, maxFillColor)); SVGStringBuilder.Append("</g> \n"); //chart title SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' font-size='12px' fill='#222' text-anchor='middle' font-family='sans-serif' >{2}</text>", (chartWid / 2), (30), label)); SVGStringBuilder.Append(String.Format("<line x1='{0}' y1='{1}' x2='{2}' y2='{3}' style='stroke:#888; stroke-width:1;shape-rendering: crispEdges;'/>", chartMargin + progressHeight, chartMargin, chartMargin + progressHeight, chartMargin + progressHeight + 10)); SVGStringBuilder.Append(String.Format("<line x1='{0}' y1='{1}' x2='{2}' y2='{3}' style='stroke:#888; stroke-width:1;shape-rendering: crispEdges;'/>", chartMargin + progressHeight + chartWidth, chartMargin, chartMargin + progressHeight + chartWidth, chartMargin + progressHeight + 10)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px; ' text-anchor='middle'>{2}</text>", chartMargin + progressHeight, chartMargin + progressHeight + 20, minValue)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#888; font-family: sans-serif; font-size: 10px; ' text-anchor='middle'>{2}</text>", chartMargin + progressHeight + chartWidth, chartMargin + progressHeight + 20, maxValue)); SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' style='fill:#333; font-family: sans-serif; font-size: 13px; ' text-anchor='middle'>{2}</text>", chartMargin + progressHeight + chartWidth / 2, chartMargin + progressHeight + 20, valueToMonitor)); SVGStringBuilder.Append("</svg>"); var SVGContent = SVGStringBuilder.ToString(); if (saveAsSVGOption != 0) { var file = CreateNewSVGFile(saveLocation, "scatterPlot"); file.WriteLine(SVGContent); file.Close(); } XmlDocument doc = new XmlDocument(); doc.LoadXml(SVGContent); Svg.SvgDocument svgdoc = new Svg.SvgDocument(); var xmlStream = new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(doc.InnerXml)); svgdoc = Svg.SvgDocument.Open(xmlStream); var imageStream = new System.IO.MemoryStream(); svgdoc.Draw().Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp); System.Drawing.Bitmap imageFile = new System.Drawing.Bitmap(imageStream); return(imageFile); }
public VPathGroupSVGGenerator(Svg.SvgDocument svg) { _Svg = svg; }
public ActionResult Get() { string requestBody; using (StreamReader sr = new StreamReader(Request.Body)) { requestBody = sr.ReadToEnd(); } if (string.IsNullOrEmpty(requestBody)) { return(new BadRequestObjectResult("No content, expected SVG content")); } LogInformation($"Processing content with length: " + requestBody.Length); LogInformation(requestBody); var xd = new System.Xml.XmlDocument(); try { xd.LoadXml(requestBody); LogInformation("XML Document parsed"); } catch (Exception ex) { return(new BadRequestObjectResult($"The provided content was not a valid XML: {ex.Message}")); } Svg.SvgDocument d = null; try { d = Svg.SvgDocument.Open(xd); LogInformation("SVG Document loaded"); } catch (Exception ex) { return(new BadRequestObjectResult($"Could not render bitmap: {ex.Message}")); } byte[] res; try { if (d == null) { throw new Exception("Image was null?"); } var b = d.Draw(); LogInformation("Drawn to the canvas"); using (var ms = new MemoryStream()) { LogInformation("Trying to write to memory"); b.Save(ms, ImageFormat.Png); LogInformation("Written to memory"); res = ms.ToArray(); } } catch (Exception ex) { return(new BadRequestObjectResult($"Cannot render image: {ex.Message}")); } return(File(res, "image/png")); }
/// <summary> /// Scale and translate structure and format into buffer /// </summary> /// <param name="mol">The structure</param> /// <param name="cellStyle">Style/conditional formatting to apply to cell</param> /// <param name="commandChar">Command character to use in buffer</param> /// <param name="x">Coordinate of left side of structure</param> /// <param name="width">Width of molecule box in milliinches</param> /// <param name="r">Row in buffer to put on. If less than 0 then return formatted data</param> /// <param name="heightInLines">number of lines used</param> public FormattedFieldInfo FormatStructure( MoleculeMx mol, CellStyleMx cellStyle, char commandChar, int x, int width, int r, ResultsField rfld = null, DataRowMx dataRow = null) { Rectangle destRect, boundingRect; int height; // formatted height in milliinches bool markBoundaries; int fixedHeight; Bitmap bm; Font font; string txt, molfile, molString = "", svg, cid = null; int translateType, desiredBondLength = 100; int pixWidth = 0, pixHeight = 0; bool debug = DataTableManager.DebugDetails; if (debug) { DebugLog.Message("=============================== FormattingStructure ==============================="); } PerformanceTimer pt = PT.Start("FormatStructure"); Stopwatch swTotal = Stopwatch.StartNew(); Stopwatch sw = Stopwatch.StartNew(); try { MoleculeFormat initialCsType = mol.PrimaryFormat; string initialCsValue = mol.PrimaryValue; QueryColumn qc = (rfld != null) ? rfld.QueryColumn : null; FormattedFieldInfo ffi = new FormattedFieldInfo(); if (dataRow != null) // get any cid in row { int ki = DataTableManager.DefaultKeyValueVoPos; if (ki < dataRow.Length) { cid = dataRow[ki] as string; } } //DebugLog.Message("FormatStructure " + cid); //if (!Rf.Grid) x = x; // debug /////////////////////////////////// // Highlight structure /////////////////////////////////// if (StructureHighlightPssc != null) { ParsedStructureCriteria pssc = StructureHighlightPssc; // Hilight substructure search match if (pssc.SearchType == StructureSearchType.Substructure || // regular SSS pssc.SearchTypeUnion == StructureSearchType.Substructure) // handles related search for just SSS to get hilighting { if (HighlightStructureMatches) { try { mol = StrMatcher.HighlightMatchingSubstructure(mol); if (DebugMx.False) // debug { //string highlightChildren = mol.MolLib.HighlightChildren; //Color highlightColor = mol.MolLib.HighlightColor; if (debug) { DebugLog.StopwatchMessage("tHilight", sw); } } } catch (Exception ex) { ex = ex; } } if (AlignStructureToQuery) { try { mol = StrMatcher.AlignToMatchingSubstructure(mol); if (debug) { DebugLog.StopwatchMessage("tOrient", sw); } } catch (Exception ex) { ex = ex; } } } // Hilight SmallWorld structure match else if (pssc.SearchType == StructureSearchType.SmallWorld) // Hilight SmallWorld structure search results { if (SmallWorldDepictions == null) { SmallWorldDepictions = new SmallWorldDepictions(); } SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters; //DebugLog.Message("Depict " + cid + ", Hilight " + swp.Highlight + ", Align " + swp.Align); // + "\r\n" + new StackTrace(true)); if ((swp.Highlight || swp.Align) & Lex.IsDefined(cid)) // call depiction for these { svg = SmallWorldDepictions.GetDepiction(cid, swp.Highlight, swp.Align); if (Lex.IsDefined(svg)) // have depiction? { { pixWidth = MoleculeMx.MilliinchesToPixels(width); bm = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth); ffi.FormattedBitmap = mol.FormattedBitmap = bm; // store in formatting info and chem structure return(ffi); } } else if (svg == null) // start retrieval of this decpiction type & fall through to get default structure initially { SmallWorldDepictions.StartDepictionRetrieval(Qm, StructureHighlightQc, swp.Highlight, swp.Align); } else { } // tried to get it but failed, fall through to get basic structure } } else if (mol.AltFormDefined("Svg")) // svg form exist (e.g. SmallWorld or "related" structure search)? { svg = mol.SvgString; if (Lex.IsDefined(svg)) { pixWidth = MoleculeMx.MilliinchesToPixels(width); bm = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth); ffi.FormattedBitmap = mol.FormattedBitmap = bm; // store in formatting info and chem structure return(ffi); } } } /////////////////////////////////// // Handle each output device /////////////////////////////////// ffi.HeightInLines = 1; // min of 1 line if (Rf.SdFile) { FormatSdfileStructure(mol); return(null); } int pageHeight = 11000; if (Rf.PageMargins != null) { pageHeight = Rf.PageMargins.Top + Rf.PageHeight + Rf.PageMargins.Bottom; } if (Rf.Excel || Rf.Word) { translateType = 2; } else { translateType = 0; } if (!Rf.FixedHeightStructures) { fixedHeight = 0; // not fixed height } else if (Rf.Excel || Rf.Word) { fixedHeight = 1; // always fixed height } else { fixedHeight = 2; // fixed height unless need to expand } if (Rf.Word && Rf.FixedHeightStructures) { markBoundaries = true; } else { markBoundaries = false; } destRect = new Rectangle(0, 0, width, width * 4 / 5); // default dest rect /////////////////////////////////////////////////////////////////////////// // Tempory fake generation of HELM & associatedimage for biopolymer testing /////////////////////////////////////////////////////////////////////////// //if (MoleculeMx.HelmEnabled == DebugMx.False) // artificially generate helm molecules // MoleculeMx.SetMoleculeToTestHelmString(mol.GetCorpId().ToString(), mol); /////////////////////////////////////////////////////////////////////////// // End of tempory fake generation of HELM & associatedimage for biopolymer testing /////////////////////////////////////////////////////////////////////////// bool fitStructure = true; if (mol.IsChemStructureFormat) { if (Rf.Grid) // special scale for grid { double scale = (float)width / MoleculeMx.StandardBoxWidth; desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale)); //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0)); desiredBondLength = (int)(desiredBondLength * 90.0 / 100.0); // scale down a bit for grid if (debug) { DebugLog.StopwatchMessage("tAdjustBondLength1", sw); } } else // set desired bond length based on page scaling { float scale = (float)width / MoleculeMx.StandardBoxWidth; desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale)); //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0)); if (debug) { DebugLog.StopwatchMessage("tAdjustBondLength2", sw); } } if (desiredBondLength < 1) { desiredBondLength = 1; } if (debug) { DebugLog.StopwatchMessage("tBeforeFit", sw); } if (fitStructure) { mol.CdkMol.FitStructureIntoRectangle // scale and translate structure into supplied rectangle. (ref destRect, desiredBondLength, translateType, fixedHeight, markBoundaries, pageHeight, out boundingRect); } if (debug) { DebugLog.StopwatchMessage("tFitStructure", sw); } ffi.HeightInLines = (int)(destRect.Height / Rf.LineHeight + 1); // lines needed } else if (mol.IsBiopolymerFormat) { if (mol.PrimaryFormat == MoleculeFormat.Helm && Rf.Excel) { svg = HelmControl.GetSvg(mol.HelmString); float inchWidth = width / 1000.0f; // convert width milliinches to inches Svg.SvgDocument svgDoc = SvgUtil.AdjustSvgDocumentToFitContent(svg, inchWidth, Svg.SvgUnitType.Inch); RectangleF svgbb = svgDoc.Bounds; float ar = svgbb.Width / svgbb.Height; // aspect ratio of svg bounding box height = (int)(width / ar); // height in milliinches ffi.HeightInLines = (int)(height / Rf.LineHeight) + 1; // lines needed destRect = new Rectangle(0, 0, width, height); } } ////////////////////////// /// Output to Grid ////////////////////////// if (Rf.Grid) { pixWidth = MoleculeMx.MilliinchesToPixels(destRect.Width); pixHeight = MoleculeMx.MilliinchesToPixels(destRect.Height); if (cellStyle == null) { if (Qm == null || Qm.MoleculeGrid == null) { font = new Font("Tahoma", 8.25f); } else { font = new Font(Qm.MoleculeGrid.Font, FontStyle.Underline); } cellStyle = new CellStyleMx(font, Color.Blue, Color.Empty); } if (mol.IsChemStructureFormat) // molfile type molecule { if (debug) { DebugLog.StopwatchMessage("tBeforeGetDisplayPreferences", sw); } DisplayPreferences dp = mol.GetDisplayPreferences(); if (debug) { DebugLog.StopwatchMessage("tGetDisplayPreferences", sw); } //desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange(desiredBondLength); // be sure bond len within allowed range //if (debug) DebugLog.StopwatchMessage("tAdjustBondLengthToValidRange", sw); //dp.StandardBondLength = MoleculeMx.MilliinchesToDecipoints(desiredBondLength); bm = mol.CdkMol.GetFixedHeightMoleculeBitmap(pixWidth, pixHeight, dp, cellStyle, mol.Caption); if (debug) { DebugLog.StopwatchMessage("tGetBitmap", sw); } } else if (mol.IsBiopolymerFormat) // Output HELM image for biopolymer { pixWidth = MoleculeMx.MilliinchesToPixels(width); bm = HelmConverter.HelmToBitmap(mol, pixWidth); } else { bm = new Bitmap(1, 1); } ffi.FormattedBitmap = mol.FormattedBitmap = bm; // store in formatting & structure ffi.FormattedText = "Formatted"; // indicate formatted (could save structure string but not needed and avoids possible conversion overhead) return(ffi); } ////////////////////////// /// Output to Html ////////////////////////// else if (Rf.Html) { if (r >= 0) { AssureTbFree(0, r + ffi.HeightInLines - 1); } if (mol.IsChemStructureFormat) { FormatChemStructureHtml(mol, destRect, width, r); } else if (mol.IsBiopolymerFormat) { FormatBiopolymerStructureHtml(mol, destRect, width, r); } if (debug) { DebugLog.StopwatchMessage("tFormatHtmlStructure", sw); } ffi.FormattedBitmap = mol.FormattedBitmap; ffi.FormattedText = mol.FormattedText; return(ffi); } ///////////////////////////////////////////////////////////////// /// Other format, store Smiles or Helm & any cellStyle in buffer ///////////////////////////////////////////////////////////////// else { if (mol.IsChemStructureFormat) { if (Rf.ExportStructureFormat == ExportStructureFormat.Smiles) { molString = mol.GetSmilesString(); } else { molString = mol.GetChimeString(); // use Chime if not smiles } } else if (mol.IsBiopolymerFormat) { molString = mol.PrimaryValue; // usually Helm but could be sequence } txt = String.Format("{0} {1} {2} {3} {4} {5} {6}", x, width, destRect.Left, destRect.Top, destRect.Right, destRect.Bottom, molString); if (cellStyle != null) // apply style to cell? { txt += " <CellStyle " + cellStyle.Serialize() + ">"; } txt = commandChar + " " + txt + "\t"; if (r >= 0) { AssureTbFree(0, r + ffi.HeightInLines - 1); Tb.Lines[r] += txt; // put in buffer } else { return(new FormattedFieldInfo(txt)); // just return formatting } } return(null); } catch (Exception ex) { DebugLog.Message(DebugLog.FormatExceptionMessage(ex)); return(null); } finally { pt.Update(); int formatCount = pt.Count; //ClientLog.Message(pt.ToString() + ", " + cs.GetMolHeader()[2]); // + ", " + new StackTrace(true)); if (debug) { DebugLog.StopwatchMessage("tTotalTime", swTotal); } } }
public static System.Drawing.Bitmap create(IList <String> Items, IList <double> Values, List <object> chartOptions = null) { //sanitize the incoming data if (Items.Count() <= 0 || Values.Count() <= 0) { throw new ArgumentException("The inputs need to be at least 1 item."); } if (Values.GetType() != typeof(double[])) { throw new ArgumentException("Currently only numbers are supported on the values, sorry!"); } if (Items.GetType() != typeof(string[])) { throw new ArgumentException("Only Strings are allowed for the items, sorry!"); } string chartTitle; int chartAreaWidth; int chartAreaHeight; int interactiveOption; int saveAsSVGOption; string saveLocation; if (chartOptions.Count == 6) { chartTitle = chartOptions[0].ToString(); chartAreaWidth = Convert.ToInt32(chartOptions[1]); chartAreaHeight = Convert.ToInt32(chartOptions[2]); interactiveOption = Convert.ToInt32(chartOptions[3]); saveAsSVGOption = Convert.ToInt32(chartOptions[4]); saveLocation = chartOptions[5].ToString(); } else { chartTitle = "Chart title"; chartAreaWidth = 500; chartAreaHeight = 500; interactiveOption = 0; saveAsSVGOption = 0; saveLocation = "Desktop"; } if (saveLocation == "" || string.Compare(saveLocation, "Desktop") == 0 || saveLocation == null) { saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } var chartWid = chartAreaWidth; var chartHei = chartAreaHeight; var chartCenterXY = chartWid / 2; var chartRad = chartWid / 2 - 40; var legendWid = 200; var legendHei = chartAreaHeight; // the chart is 400px by 400px and the legend is 200px by 400px var SVGStringBuilder = new StringBuilder(); SVGStringBuilder.Append(String.Format("<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='{0}px' height='{1}px' viewBox='0 0 {0} {1}' xml:space='preserve' >\n", (chartWid + legendWid), chartHei)); //var SVGContent = "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='" + (chartWid + legendWid) + "px' height='" + chartHei + "px' viewBox='0 0 " + (chartWid + legendWid) + " " + chartHei + "' xml:space='preserve' > \n"; //draw graph background. The plot is always 500pt by 500pt SVGStringBuilder.Append(String.Format("<rect x='0' y='0' width='{0}' height='{1}' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n", chartWid, chartHei)); //SVGContent += "<rect x='0' y='0' width='" + chartWid + "' height='" + chartHei + "' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n"; SVGStringBuilder.Append(String.Format("<rect x='{0}' y='0' width='{1}' height='{2}' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n", chartWid, legendWid, legendHei)); //SVGContent += "<rect x='" + chartWid + "' y='" + 0 + "' width='" + legendWid + "' height='" + legendHei + "' style='fill:#FAFAFA; stroke-width:1px; stroke: #EEE' />\n"; //calculate the % of each of the items List <double> percentages = new List <double>(); double sum = Values.Sum(); foreach (var value in Values) { percentages.Add((value * Math.PI * 2) / sum); } double lastPercentage = -1 * Math.PI / 2; string[] color = new string[] { "71d0f4", "e16452", "74c493", "f2d435", "8361a9", "9abf88", "ef778c", "5698c4", "8c4646", "578b7e", "cbc49d", "ef464c", "a8c542", "322f28", "9f3169", "e99123", "878787", "6e8314", "2854a4", "555555" }; var i = 0; var j = 0; //generate charts foreach (var percentage in percentages) { var fillColor = color[i]; if (i >= 19) { i = 0; } var largeArcFlag = (percentage < Math.PI) ? 0 : 1; SVGStringBuilder.Append(String.Format("<path id='pieChartSector{0}' d='M {1},{1} l {2},{3} A{4},{4} {5} {6},1 {7},{8} z' fill='#{9}' />\n", i, chartCenterXY, chartRad * Math.Cos(lastPercentage), chartRad * Math.Sin(lastPercentage), chartRad, lastPercentage, largeArcFlag, (chartCenterXY + chartRad * Math.Cos(lastPercentage + percentage)), (chartCenterXY + chartRad * Math.Sin(lastPercentage + percentage)), fillColor)); /*SVGContent += "<path id='pieChartSector" + i + "' d='M " + chartCenterXY + "," + chartCenterXY + * " l " + chartRad * Math.Cos(lastPercentage) + "," + chartRad * Math.Sin(lastPercentage) + * " A" + chartRad + "," + chartRad + " " + lastPercentage + " " + largeArcFlag + ",1 " + (chartCenterXY + chartRad * Math.Cos(lastPercentage + percentage)) + "," + (chartCenterXY + chartRad * Math.Sin(lastPercentage + percentage)) + " z' fill='#" + fillColor + "' stroke='rgba(0, 0, 0, 0.4)' stroke-width='0' />\n"; */ if (interactiveOption != 0) { SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' fill='#444444' visibility='hidden' font-family='sans-serif' font-size='12'>{2} ({3})", ((chartCenterXY + chartRad * Math.Cos(lastPercentage + percentage / 2))), ((chartCenterXY + chartRad * Math.Sin(lastPercentage + percentage / 2))), Items[j], Values[j])); //SVGContent += "<text x='" + ((chartCenterXY + chartRad * Math.Cos(lastPercentage + percentage / 2))) + "' y='" + ((chartCenterXY + chartRad * Math.Sin(lastPercentage + percentage / 2))) + "' fill='#444444' visibility='hidden' font-family='sans-serif' font-size='12'>" + " " + Items[j] + " (" + Values[j] + ")"; SVGStringBuilder.Append(String.Format("<set attributeName='visibility' from='hidden' to='visible' begin='pieChartSector{0}.mouseover' end='pieChartSector{0}.mouseout'/>", i)); //SVGContent += "<set attributeName='visibility' from='hidden' to='visible' begin='pieChartSector" + i + ".mouseover' end='pieChartSector" + i + ".mouseout'/>"; SVGStringBuilder.Append("</text>"); //SVGContent += "</text>"; } lastPercentage += percentage; ++j; ++i; } var margin = 20; SVGStringBuilder.Append(String.Format("<text x='{0}' y='15' fill='#444444' font-family='sans-serif' font-size='12' text-anchor='middle'>{1}</text>", (chartWid / 2), chartTitle)); //SVGContent += "<text x='" + (chartWid / 2) + "' y='" + 15 + "' fill='#444444' font-family='sans-serif' font-size='12' text-anchor='middle'>" + chartTitle + "</text>"; i = 0; j = 0; //generate legend for the chart foreach (var item in Items) { if (i >= 20) { i = 0; } var centage = Math.Round((percentages[i] / (Math.PI * 2)) * 100, 2); SVGStringBuilder.Append(String.Format("<rect x='{0}' y='{1}' width='20' height='20' rx='10' ry='10' fill='#{2}' />\n", (chartWid + margin), ((i * 25) + 50), color[i])); //SVGContent += "<rect x='" + (chartWid + margin) + "' y='" + ((i * 25) + 50) + "' width='20' height='20' rx='10' ry='10' fill='#" + color[i] + "' />\n"; SVGStringBuilder.Append(String.Format("<text x='{0}' y='{1}' fill='#444444' font-family='sans-serif' font-size='12'> {2}% {3} ({4})</text>", (chartWid + margin + 25), ((i * 25) + 50 + 15), centage, item, Values[j])); //SVGContent += "<text x='" + (chartWid + margin + 25) + "' y='" + ((i * 25) + 50 + 15) + "' fill='#444444' font-family='sans-serif' font-size='12'>" + " " + centage + "% " + item + " (" + Values[j] + ")</text>"; i = i + 1; ++j; } //close the svg SVGStringBuilder.Append("</svg>"); var SVGContent = SVGStringBuilder.ToString(); if (saveAsSVGOption != 0) { var file = CreateNewSVGFile(saveLocation, "pieChartPlot"); file.WriteLine(SVGContent); file.Close(); } XmlDocument doc = new XmlDocument(); doc.LoadXml(SVGContent); Svg.SvgDocument svgdoc = new Svg.SvgDocument(); var xmlStream = new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(doc.InnerXml)); svgdoc = Svg.SvgDocument.Open(xmlStream); var imageStream = new System.IO.MemoryStream(); svgdoc.Draw().Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp); System.Drawing.Bitmap imageFile = new System.Drawing.Bitmap(imageStream); return(imageFile); /* * //export as a SVG in desktop * var file = CreateNewSVGFile(saveLocation, "pieChart"); * file.WriteLine(SVGContent); * file.Close();*/ }
private void PreviewCenterline(Bitmap bmp) { if (!System.IO.Directory.Exists(".//Autotrace//TempFolder//")) { System.IO.Directory.CreateDirectory(".//Autotrace//TempFolder//"); } string fname = $".//Autotrace//TempFolder//{System.IO.Path.GetRandomFileName()}"; try { bmp.Save($"{fname}.bmp", System.Drawing.Imaging.ImageFormat.Bmp); System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; string dst = (despeckletightness.Value / 10.0).ToString("0.00", nfi); string ieth = (trackBar6.Value / 10.0).ToString("0.00", nfi); string liner = (linereversionthreshold.Value / 10.0).ToString("0.00", nfi); string linet = (linethreshold.Value / 10.0).ToString("0.00", nfi); string command = ".//Autotrace//autotrace.exe"; string rparam = $"-corner-a {corneralwaysthreshold.Value} -corner-t {cornerthreshold.Value} -corner-s {cornersurround.Value} -despeckle-l {despecklelevel.Value} -despeckle-t {dst} -filter-i {filteriterations.Value} -line-r {liner} -line-t {linet} -tangent-s {tangentsurround.Value}"; if (preservewidth.Checked) { rparam = rparam + " -preserve-width"; } if (removeadjacentcorners.Checked) { rparam = rparam + " -remove-adjacent-corners"; } string param = $"-output-fi {fname}.svg -output-fo svg -centerline {rparam} {fname}.bmp"; label1.Text = rparam; Debug.WriteLine(param); ExecuteCommand(command, param); string fcontent = System.IO.File.ReadAllText($"{fname}.svg"); fcontent = colorRegex.Replace(fcontent, "stroke:#FF0000;"); Svg.SvgDocument svg = Svg.SvgDocument.FromSvg <Svg.SvgDocument>(fcontent); using (Graphics g = Graphics.FromImage(bmp)) { g.FillRectangle(new SolidBrush(Color.FromArgb(200, Color.White)), g.ClipBounds); svg.Draw(g); } } catch (Exception) { } finally { try { if (System.IO.File.Exists($"{fname}.bmp")) { System.IO.File.Delete($"{fname}.bmp"); } } catch { } try { if (System.IO.File.Exists($"{fname}.svg")) { System.IO.File.Delete($"{fname}.svg"); } } catch { } } }