Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        /*
         * 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;
                    }
                }
            }
        }
Exemplo n.º 3
0
        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);
        }
        public List <VPathGroup> GenerateVPathGroups()
        {
            SvgToVPathRenderer gr = new SvgToVPathRenderer(_Svg.Ppi / 25.4);

            _Svg.Draw(gr);

            return(gr.GetResult());
        }
Exemplo n.º 5
0
        /// <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()));
            }
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        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 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));
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 11
0
        /*
         * 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);
            }
        }
Exemplo n.º 12
0
        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 { }
            }
        }
Exemplo n.º 13
0
        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();*/
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        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);
        }
Exemplo n.º 17
0
        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"));
        }
Exemplo n.º 18
0
        private void ShowView()
        {
            foreach (string id in m_IdList)
            {
                Svg.SvgElement group = m_SvgDocument.GetElementById(id);

                if (group == null)
                {
                    continue;
                }

                foreach (var item in group.Children)
                {
                    if (!item.ContainsAttribute("name"))
                    {
                        continue;
                    }

                    if (item is Svg.SvgText)
                    {
                        if ((item as Svg.SvgText).ContainsAttribute("name"))
                        {
                            var tempResult = m_TopologicalValues.Find(result => result.MeterCode == id && result.ParamCode.ToLower() == item.CustomAttributes["name"].ToString().ToLower());
                            if (tempResult != null)
                            {
                                switch ((item as Svg.SvgText).CustomAttributes["name"].ToString().ToLower())
                                {
                                case "ua":
                                case "ub":
                                case "uc":
                                case "uab":
                                case "ubc":
                                case "uca":
                                    (item as Svg.SvgText).Text = tempResult.Value + " V";
                                    break;

                                case "ia":
                                case "ib":
                                case "ic":
                                    (item as Svg.SvgText).Text = tempResult.Value + " A";
                                    break;
                                }
                            }
                        }
                    }
                    else if (item is Svg.SvgGroup)
                    {
                        if ((item as Svg.SvgGroup).ContainsAttribute("name"))
                        {
                            if ((item as Svg.SvgGroup).CustomAttributes["name"].ToString().ToLower() == "on")
                            {
                                item.Opacity = 1;
                            }
                            else if ((item as Svg.SvgGroup).CustomAttributes["name"].ToString().ToLower() == "off")
                            {
                                item.Opacity = 0;
                            }
                        }
                    }
                }
                //if()
            }

            if (!m_ViewStatus)
            {
                return;
            }
            this.picView.Image = m_SvgDocument.Draw();
        }