2

I want to convert png to base64 and insert the encoded string in an svg.

fIm = open('name.png', 'rb')
dataIm = fIm.read().encode("base64").replace('\n','')
baseIm += '<g id="%s"><image xlink:href="data:image/png;base64,%s" width="%s" height="%s"/></g>' % (newVal, dataIm, curX, curY)

The result image does not display.

What's the problem?

Here's the output svg file:

<?xml version='1.0' ?>
<svg viewBox='0 0 200 200' width='200' height='200' xmlns='http://www.w3.org/2000/svg'>
<defs><g  id="name">
<image xlink:href="data:image/png;base64,..." width='20' height='20'/>
</g></defs>
<use xlink:href="#name" x='30' y='30' />
</svg>

solution

fIm = open('switchToMinus.png', 'rb')
dataIm = fIm.read().encode("base64").replace('\n','')
addText = '<image xlink:href="data:image/png;base64,{0}" width="20" height="20" x="40" y="40" />'.format(dataIm)
startSvg = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="240px" height="240px" viewBox="0 0 240 240">
"""

endSvg = """
</svg>
"""

if __name__ == '__main__':
    f = open('image2.svg','w')
    f.write( startSvg + addText + endSvg )
    f.close()
    print 'Okay!'
vinni_pux
  • 165
  • 1
  • 1
  • 7
  • Hard to tell from just this code. The `` tag and the data creation looks basically OK -- assuming `curX` and `curY` are reasonable value and it's encoding a valid .png file -- so it seems likely to be something else, like what your `` tag's `width`, `height`, or `viewbox` attribute settings that are causing the image to not be displayed. Please should the contents of the complete file in your question. – martineau Jan 24 '13 at 10:35
  • Wait, I think you're missing a double quote at the end of the base64 data, so that part should be `......` – martineau Jan 24 '13 at 10:42
  • Thank, but it is not missing double quotes. – vinni_pux Jan 24 '13 at 10:58
  • 1
    You're missing an `xmlns:xlink="http://www.w3.org/1999/xlink"` on the root element. – Erik Dahlström Jan 24 '13 at 11:43
  • Yes, it is right. Thanks to all. – vinni_pux Jan 24 '13 at 12:25
  • Sorry, you _were_ missing the double quote at the end of the `"data:image/png;base64,%s"` portion when I wrote the comment. Apparently that wasn't the whole problem. – martineau Jan 24 '13 at 16:15
  • +1 for showing the solution. – martineau Jan 24 '13 at 16:33

0 Answers0