Converting SVG to PNG using C# [closed]
I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this?
Solution 1:
There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code
var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(path, ImageFormat.Png);
}
Solution 2:
You can call the command-line version of inkscape to do this:
http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx
Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:
Original Project
http://www.codeplex.com/svg
Fork with fixes and more activity: (added 7/2013)
https://github.com/vvvv/SVG
Solution 3:
When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string pathname);
[DllImport("libgobject-2.0-0.dll", SetLastError = true)]
static extern void g_type_init();
[DllImport("librsvg-2-2.dll", SetLastError = true)]
static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);
[DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);
public static void RasterizeSvg(string inputFileName, string outputFileName)
{
bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin");
if (!callSuccessful)
{
throw new Exception("Could not set DLL directory");
}
g_type_init();
IntPtr error;
IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);
if (error != IntPtr.Zero)
{
throw new Exception(Marshal.ReadInt32(error).ToString());
}
callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null));
if (!callSuccessful)
{
throw new Exception(error.ToInt32().ToString());
}
}