Java & SVG using the img tag

1.6k views Asked by At

In reference to this post

I am creating a charting engine and I have everything setup where a GET request returns an SVG. I am using JFreeSVG (extremely similar to Batik). I can render the SVG using a iframe and object HTML tag. I want to use a img tag to create the svg image, but it gives me a blank box. I have scoured the web and truly cannot find anything and you are my last hope.

Here is an example of what my request returns:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:jfreesvg="http://www.jfree.org/jfreesvg/svg" width="423" height="452" text-rendering="auto" shape-rendering="auto">
<rect x="0" y="0" width="423" height="452" style="fill: rgb(255,255,255); fill-opacity: 1.0" transform="matrix(1,0,0,1,0,0)" clip-path="url(#4989619974245clip-0)"/>
<g transform="matrix(1,0,0,1,0,0)">
    <text x="8" y="446.14" style="fill: rgb(0,0,0); fill-opacity: 1.0; font-family: Tahoma; font-size: 9px; " clip-path="url(#4989619974245clip-0)">November 19, 2014</text>
<g style="fill: url(#4989619974245gp0); fill-opacity: 1.0; stroke: none" transform="matrix(1,0,0,1,0,0)" clip-path="url(#4989619974245clip-1)">
<rect x="5" y="8" width="386.62" height="412.27" style="stroke-width: 1.0;stroke: rgb(204,204,204);stroke-opacity: 1.0;; fill: none" transform="matrix(1,0,0,1,0,0)" clip-path="url(#4989619974245clip-0)"/>
</svg>
1

There are 1 answers

0
Sep On

The best solution is to pass the image as Base64 using URI. Base64 is desirable because of its compatibility with browsers (IE9)

        //g2.getSVGEleemnt returns a SVG in string eg. <svg> ... </svg>
        String imageString = g2.getSVGElement();
        //encode it in Base64 
        byte[] imageData = Base64.encodeBase64(imageString.getBytes());
        //indicate mime type && base64
        String header = "data:image/svg+xml;base64,";
        byte[] headerData = header.getBytes();

Once you have, you have to stream the header and then the image data in that order. Place your data or your call that gets data in the img tag and Viola!

<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaH........">