Search code examples
rubysvgutf-8decodingdata-uri

how to decode svg data uri (not base64)


I have the svg data uri:

"data:image/svg+xml;charset=utf8,%3Csvgxmlns='http://www.w3.org/2000/svg'width='18'height='36'viewBox='001836'%3E%3Cpathd='M15.70714.293l-2.82-2.82C13.58510.493149.296148c0-3.314-2.686-6-6-6S24.68628s2.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM812c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='%23000'/%3E%3Cpathd='M15.70732.293l-2.82-2.82C13.58528.4931427.2961426c0-3.314-2.686-6-6-6s-62.686-662.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM830c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='red'/%3E%3C/svg%3E"

Help me please to decode it to svg file. I have no problem with decoding base64 data uri using 'data_uri' gem, but if I try with optimized url encoded, I have an error:

ArgumentError: unknown encoding name - utf8


Solution

  • This looks like it's just URL-encoded:

    require 'uri'
    
    uri = "data:image/svg+xml;charset=utf8,%3Csvgxmlns='http://www.w3.org/2000/svg'width='18'height='36'viewBox='001836'%3E%3Cpathd='M15.70714.293l-2.82-2.82C13.58510.493149.296148c0-3.314-2.686-6-6-6S24.68628s2.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM812c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='%23000'/%3E%3Cpathd='M15.70732.293l-2.82-2.82C13.58528.4931427.2961426c0-3.314-2.686-6-6-6s-62.686-662.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM830c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='red'/%3E%3C/svg%3E"
    
    data = URI.decode(uri.split(',', 2)[1])
    puts data
    # =>  <svgxmlns='http://www.w3.org/2000/svg'width='18'height='36'viewBox='001836'><pathd='M15.70714.293l-2.82-2.82C13.58510.493149.296148c0-3.314-2.686-6-6-6S24.68628s2.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM812c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='#000'/><pathd='M15.70732.293l-2.82-2.82C13.58528.4931427.2961426c0-3.314-2.686-6-6-6s-62.686-662.686666c1.29602.492-.4153.473-1.113l2.822.82c.195.195.45.293.707.293.2570.512-.098.707-.293.39-.39.39-1.0230-1.414zM830c-2.2060-4-1.794-4-4s1.794-44-441.79444-1.7944-44z'fill='red'/></svg>