Daniel Hitchcock Daniel Hitchcock - 2 months ago 20
Javascript Question

ReactJS, rendering base64 string in <img> tag gives error ERR_INVALID_URL

I am attempting to render a few server generated images (matplotlib graphs to be specific) to a ReactJS module without saving files on the server. The approach I took was to use base64 to generate an image string.

When the time comes to render my image in a React component, I use:

const chart1 ="data:image/png;base64," + this.props.matchPlot1
return <div>
<img src={chart1} />

but unfortunately I am greeted with:

GET data:image/png;base64,b'iV... ...CYII=' net::ERR_INVALID_URL

in the javascript console. From what I understand, somewhere along the line the the resulting HTML thinks that I'm specifying an external hyperlink, when in fact I just want to use the actual decoded base64 string as the image. I have seen solutions for Angular (img ng-src="") and for React-Native (Image /), but haven't found a solution for ReactJS.

I am using ReactJS 15.1.0 and JSXTransformer v0.13.3 client-side rendering. As for my webserver, if relevant, is Flask with Python3.

Any help, or alternate strategy to produce an image without saving a copy on the server is appreciated! (PS. I've used D3 to draw graphs of the data client-side, but with SVGs there are too many points and performance is terrible. I've look into converting the SVGS to canvas but it's more work than I was hoping to deal with right now)

I should have looked at the string more closely. My server response is an ajax request and in Python3 (maybe 2?) a bytestring is not json serializable. I converted it to a str as str(plots[0]). This accidentally added a b'{string}' wrapper around my base64 object, as evidenced in the console response. I guess that syntax was enough to through chrome off. That, and the red herrings with angular and react-native solutions led me to believe it was a react problem when it fact it's a pythong string problem. It's working now, and I appreciate the input.

Answer Source

Without the full string, it's hard to tell with certainty what could be wrong.

However, I think I might've found the issue:

GET data:image/png;base64,b'iV... ...CYII=' net::ERR_INVALID_URL

Based on the above error that you're getting, it looks like you might be missing an extra = at the end of your URI, depending on the length.

Try changing it so that it ends with CYII== and not CYII= as it seems to be currently.

Alternatively, the variable matchPlot1 might somehow be incorrect. If it has //, make sure to escape the comment.