其实只是做了简单封装,可以方便进行批量转换.
获取Svg对象坐标的代码请看:根据svg节点对象类型和路径值转换坐标值,
DrawingColor方法是进行颜色填充的.
/// <summary> /// svg文件转换为图片 /// </summary> /// <param name="svgContent">svg内容</param> /// <param name="svgFile">svg文件</param> /// <param name="imgType">图片类型</param> /// <returns>转换成功后的文件路径</returns> public string SvgToImage(string outputDir, string svgContent = "", string svgFile = "", ImageType imgType = ImageType.Png) { var fileInfo = new FileInfo(svgFile); string fileName = fileInfo.Name.Split('.')[0]; HtmlAgilityPack.HtmlDocument document; if (svgContent.Length > 0) { document = new HtmlAgilityPack.HtmlDocument(); document.LoadHtml(svgContent); } else { document = this.LoadDocumentFormFile(svgFile); } //初始化Svg对象 SvgObject so = new SvgObject(document.DocumentNode.WriteTo()); //获取Svg坐标对象集合 Dictionary<string, ObjectPosition> dictPosition = so.GetSvgObjectPositions(); //进行颜色填充,返回新的Svg文档 document = DrawingColor(ref document, dictPosition); //保存 document.Save(svgFile, Encoding.Default); string pngFileName = Path.Combine(outputDir, fileName + ".png"); //设置命令行参数,详情见该软件帮助文档. //string inkscapeArgs = string.Format("-f {0} -e {1} -b {2}"", svgFile, pngFileName, "#000000"); string inkscapeArgs = string.Format("inkscape {0} --export-png={1} --export-background={2}", svgFile, pngFileName, "#000"); //调用 Inkscape 进行svg转图片 try { //是否提供了自定义路径 if (this.InkscapeApplicationPath.Length == 0) this.InkscapeApplicationPath = "D:\Program Files (x86)\Inkscape\inkscape.exe"; //调用本地系统进程 Process inkscape = Process.Start(new ProcessStartInfo(this.InkscapeApplicationPath, inkscapeArgs)); inkscape.WaitForExit(3000); } catch (Exception) { return ""; } if (!System.IO.File.Exists(pngFileName)) return ""; string imageFileName = Path.Combine(outputDir, fileName + ".$"); //最后再将png文件转换成其他格式图片文件. Bitmap myImage = new Bitmap(pngFileName); ImageFormat format = ImageFormat.Png; switch (imgType) { case ImageType.Png: return pngFileName; case ImageType.Jpg: imageFileName = imageFileName.Replace("$", "jpg"); format = ImageFormat.Jpeg; break; case ImageType.Bmp: imageFileName = imageFileName.Replace("$", "bmp"); format = ImageFormat.Bmp; break; case ImageType.Gif: break; default: break; } myImage.Save(imageFileName, format); return imageFileName; }
最终图片如下:
保证两两相邻的人物填充颜色不重复.用的算法是简单的四边形是否重叠的算法.
Inkscape下载地址:
这是一个免费开源的矢量图处理软件.