1. 程式人生 > >SVG中Path Data資料簡化及資料夾所有檔案批量匯出為圖片

SVG中Path Data資料簡化及資料夾所有檔案批量匯出為圖片

先看效果圖片:

using Svg;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;

namespace SVG2Image
{
    /// <summary>
    /// 將SVG批量匯出成PNG等圖片
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        //儲存圖片路徑
        string savePath = @"d:\output";
        //簡化向量圖輸入路徑
        string savePathNew = @"d:\outputNew";
        //SVG檔案路徑
        string svgFilePath = @"d:\outputNew";
        //string svgFilePath = @"E:\介面\POD0606New\ICO";
        private void button_Click(object sender, RoutedEventArgs e)
        {
            string sizeText = textBox.Text;
            if (string.IsNullOrEmpty(sizeText)) sizeText = "64";
            string[] sizeArray = sizeText.Split(',');
            List<int> listSize = new List<int>();
            try
            {
                foreach (string s in sizeArray)
                {
                    listSize.Add(int.Parse(s));
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("輸入的尺寸有誤,必須為數字(多組用逗號隔開);\r\n" + exc.ToString());
                return;
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            string[] arraySvgFiles = Directory.GetFiles(svgFilePath, "*.svg");
            int icoCount = arraySvgFiles.Length;
            int icoAllCount = 0;
            foreach (string file in arraySvgFiles)
            {
                string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
                fileName = fileName.Replace("_New", "");

                try
                {
                    string svgFileContents = File.ReadAllText(file, Encoding.UTF8);
                    var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
                    string saveFileName = savePath + @"\" + fileName + @"{0}_{1}.png";
                    foreach (int sz in listSize)
                    {
                        using (var stream = new MemoryStream(byteArray))
                        {
                            var svgDocument = SvgDocument.Open(stream);
                            svgDocument.Width = sz;
                            svgDocument.Height = sz;
                            var bitmap = svgDocument.Draw();
                            bitmap.Save(string.Format(saveFileName, sz, sz), ImageFormat.Png);
                        }
                        icoAllCount++;
                    }
                }
                catch (Exception exc)
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath + @"\error.txt", true))
                    {
                        sw.WriteLine(fileName);// 直接追加檔案末尾,換行
                    }
                }
            }
            MessageBox.Show(string.Format("有{0}張向量標誌圖片,共生成{1}張圖片!", icoCount, icoAllCount));
        }

        /// <summary>
        /// 根據選單名稱建立空SVG內容的檔案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateSVG_Click(object sender, RoutedEventArgs e)
        {
            string menuNames = @"成品型別維護|成品維護";
            string contentTemplate = @"<svg version=""1.1"" id=""圖層_1"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"" x=""0px"" y=""0px""
     width=""648.992px"" height=""648.992px"" viewBox=""0 0 648.992 648.992"" enable-background=""new 0 0 648.992 648.992""
     xml:space=""preserve"">

</svg>";
            string[] arrayMenus = menuNames.Split('|');
            foreach (string menu in arrayMenus)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath + @"\" + menu + @".svg", true))
                {
                    sw.WriteLine(contentTemplate);// 直接追加檔案末尾,換行
                }
            }
        }

        private void btnLostSvg_Click(object sender, RoutedEventArgs e)
        {
            string[] arraySvgFiles = Directory.GetFiles(svgFilePath, "*.svg");
            List<string> listSvgFiles = new List<string>();
            foreach (string file in arraySvgFiles)
            {
                listSvgFiles.Add(System.IO.Path.GetFileNameWithoutExtension(file));
            }
            string menuNames = @"系統管理|部門維護";
            string[] arrayMenus = menuNames.Split('|');
            foreach (string menu in arrayMenus)
            {
                if (!listSvgFiles.Contains(menu))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath + @"\WithoutFile.txt", true))
                    {
                        sw.WriteLine(menu);// 直接追加檔案末尾,換行
                    }
                }
            }
        }

        private void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            //string oldContent = txtBoxOldContent.Text;
            //txtBoxResultContent.Text = GetNumberByRound(oldContent);

            if (!Directory.Exists(savePathNew))
            {
                Directory.CreateDirectory(savePathNew);
            }
            string[] arraySvgFiles = Directory.GetFiles(svgFilePath, "*.svg");

            foreach (string file in arraySvgFiles)
            {
                string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
                try
                {
                    string svgFileContents = File.ReadAllText(file, Encoding.UTF8);
                    svgFileContents = GetNumberByRound(svgFileContents);
                    string saveFileName = savePathNew + @"\" + fileName + @"_New" + System.IO.Path.GetExtension(file);
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFileName, false))
                    {
                        sw.WriteLine(svgFileContents);// 直接追加檔案末尾,換行
                    }
                }
                catch (Exception exc)
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePathNew + @"\error.txt", true))
                    {
                        sw.WriteLine(fileName);// 直接追加檔案末尾,換行
                    }
                }
            }
        }

        /// <summary>
        /// SVG程式碼簡化
        /// </summary>
        /// <param name="str">SVG程式碼</param>
        /// <returns>簡化後的程式碼</returns>
        private string GetNumberByRound(string str)
        {
            string pattern = @"([-,a-zA-Z\s]*)(\d+\.?\d*)";
            Regex r = new Regex(pattern);
            str = Regex.Replace(str, @"<!--.*-->", "");
            str = Regex.Replace(str, @"<!DOCTYPE.*>", "");
            /*
            <!-- Generator: Adobe Illustrator 14.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 43363)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
*/
            str = Regex.Replace(str, @"\r\n", "");
            string result = string.Empty;
            if (r.IsMatch(str))
            {
                MatchCollection mc = r.Matches(str);
                if (mc.Count == 0) return result;

                Dictionary<string, string> dicNum = new Dictionary<string, string>();

                foreach (Match m in mc)
                {
                    GroupCollection colls = Regex.Match(m.Value, pattern).Groups;
                    string v = string.Empty;
                    if (colls.Count > 1)
                    {
                        //foreach (Group item in colls)
                        {
                            //Console.WriteLine(item.Value.ToString());
                            string k = colls[0].Value;
                            v = colls[2].Value;
                            if (!string.IsNullOrEmpty(v) && !dicNum.ContainsKey(k))
                            {
                                dicNum.Add(k, colls[1].Value + Math.Round(Convert.ToDecimal(v), 1, MidpointRounding.AwayFromZero).ToString());
                            }
                        }
                    }
                    else
                    {
                        v = m.Value;
                        if (!string.IsNullOrEmpty(v) && !dicNum.ContainsKey(v))
                        {
                            dicNum.Add(v, Math.Round(Convert.ToDecimal(v), 1, MidpointRounding.AwayFromZero).ToString());
                        }
                    }

                }
                foreach (string key in dicNum.Keys)
                {
                    str = str.Replace(key, dicNum[key]);
                    //using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savePath + @"\Keys.txt", true))
                    //{
                    //    sw.WriteLine(key +"\t" + dicNum[key]);// 直接追加檔案末尾,換行
                    //}
                }

                result = str;
            }
            else { result = str; }

            return result.Replace("http://www.w3org/", "http://www.w3.org/");
        }
    }
}