dlemstra / Magick.NET

The .NET library for ImageMagick
Apache License 2.0
3.43k stars 413 forks source link

SVG not being converted to PNG correctly #919

Open akilburge opened 3 years ago

akilburge commented 3 years ago

Prerequisites

Description

I'm seeing a weird results (png is getting clipped) when converting a particular SVG into PNG using Magick.NET (same issue using imagemagick from the console). The PNG is converted properly if a viewBox is defined in the SVG.

Steps to Reproduce

Run the following code:

using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using ImageMagick;

namespace ConsoleApp7
{
    class Program
    {
        static async Task Main()
        {
            var httpClient = new HttpClient();

            // #1 - No ViewBox but png converted correctly
            var svg1 = await httpClient.GetStringAsync("https://img.vggcdn.net/svgv2/156660.svg?v=47");
            ConvertSvgToPng(svg1, "./1-svg-no-viewbox-but-converted-correctly.png");

            // #2 - No ViewBox but png converted incorrectly
            var svg2 = await httpClient.GetStringAsync("https://img.vggcdn.net/svgv2/195035.svg?v=14");
            ConvertSvgToPng(svg2, "./2-svg-no-viewbox-but-converted-incorrectly.png");

            // #3 - ViewBox and png converted correctly
            var svg3 = svg2.Replace("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">", "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"281 11 962 995\">");
            ConvertSvgToPng(svg3, "./3-svg-viewbox-and-converted-correctly.png");
        }

        static void ConvertSvgToPng(string svg, string fileName)
        {
            var settings = new MagickReadSettings { Format = MagickFormat.Svg, BackgroundColor = MagickColors.Transparent };
            using (var image = new MagickImage(Encoding.UTF8.GetBytes(svg), settings))
            {
                image.Write(new FileInfo(fileName), MagickFormat.Png32);
            }
        }
    }
}

System Configuration

dlemstra commented 3 years ago

It turns out that both ImageMagick and the librsvg library are using a viewbox where part of the image is outside the viewbox. This will probably not be easy to fix. I would advise you to add the viewbox when it is missing. Will leave this open in case someone wants to spend time investigating why this is happening.