简体   繁体   中英

Send image inside SVG tag to server - JavaScript

On the client side I have an svg element, under which there's an image and some text on that image (so it looks like a poster with text on it). I need to send this poster as a whole to the server. The HTML looks like this:

    <svg id="poster_svg" width="1000" height="1000" style="max-width: 100%;">
    <image href="/static/images/motiv1.jpg" width="100%" height="100%"/>
    <p class="centered" id="poster_text"></p>
    </svg>

The text inside the p is generated by some other user actions. I found a tutorial online which converts the svg element to base64 which then I can use to send to server through a POST request.

The JavaScript code for it is:

var SVGDomElement = document.getElementById("poster_svg");
var serializedSVG = new XMLSerializer().serializeToString(SVGDomElement);
var base64Data = window.btoa(serializedSVG);

const json = {
    image: base64Data
};
const options = {
    method: "POST",
    body: JSON.stringify(json),
    headers:{
        'Content-Type':'application/json'
    }
};

fetch('/makeposter',options).then(res=>{
    return res.json()
}).then(cont=>{
    console.log(cont)
});

On the server side (which uses Flask), the base64 is recieved successfully, but when converted to an image, it is blank. The server code for converting the base64 to image is this:

cont = request.get_json()
imgb64 = cont['image']
decoded = base64.b64decode(imgb64)
f=open("test.png","wb")
f.write(decoded)
f.close()

Why is the image blank, and how can I fix it?

base64-encoding does not magically convert SVG to PNG. After decoding on the server, the result will still be a string, and its content will be still the same serialized SVG you quoted for the client side.

This includes the fact that the image tag still only holds a reference to the JPG file, not the file content itself. You will need to make sure that the relative path to that file is still valid in the context of server-side execution.

Lastely, if you want to convert the result from SVG to PNG, you need some software to do the actual work. I have no further knowledge how you would go about that with Flask.

You could also do the conversion client-side, see for example this question for a how-to. Just exchange the download function described there with an upload function. But note that there is a serious caveat: the <image> href inside the SVG must point to the same domain as the page this is executed on, otherwise export will be blocked .

Aside Using a HTML <p> tag directly inside SVG content does not work. You have to use a <text> element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM