SVG to PNG batch converter (C# .NET 2012)

I had this problem a while ago, and it took quite a bit of research to see how you can batch convert SVG files to PNG using C# (since I needed to do some further manipulations on the image in the process). I used a function webpage_to_image based on Chris Pietschmann’s code, which takes a screenshot of the web browser control and returns it as a Bitmap. The full process goes like this:

Open .SVG file with browser control -> webpage_to_image-> Save Bitmap variable to a file as a PNG

        public Bitmap webpage_to_image(string url) 
        {
            
        // Based on Chris Pietschmann's code
        // URL: http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image
        // License: CC BY 3.0 US
            
            // Load the webpage into a WebBrowser control
            WebBrowser wb = new WebBrowser(); 
            wb.ScrollBarsEnabled = false; 
            wb.ScriptErrorsSuppressed = true;
            wb.Navigate(url);  
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            { System.Windows.Forms.Application.DoEvents(); }  
        
            wb.Width = 1920;
            wb.Height = 980;
            wb.ScrollBarsEnabled = false;

            Bitmap bitmap = new Bitmap(wb.Width, wb.Height); 
            wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
            wb.Dispose();  
            return bitmap;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            String path_input = "D:\\svg\\";
            String path_output = "D:\\png\\";
            String[] files = Directory.GetFiles(path_input);

            for (int i = 0; i < files.Count(); i++)
            {
                GC.Collect();
                string url = files[i];
                Bitmap thumbnail = webpage_to_image(url);
                thumbnail.Save(path_output + Path.GetFileNameWithoutExtension(files[i]) + ".png", System.Drawing.Imaging.ImageFormat.Png);
            }

        }

If CPU is your bottleneck, you can quickly improve on this by using a Parallel.For instead of the usual for loop. Also, you should modify wb.Width and wb.Height in order to change the size of the PNG file output.

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close