I'm currently working on a WebSocket application that is displaying images send by a C++ server. I've seen a couple of topics around there but I can't seem to get rid of this error in Firefox:
Image corrupt or truncated: data:image/png;base64,[some data]
Here's the Javascript code I'm using to display my blob:
socket.onmessage = function(msg) {
var blob = msg.data;
var reader = new FileReader();
reader.onloadend = function() {
var string = reader.result;
var buffer = Base64.encode(string);
var data = "data:image/png;base64,"+buffer;
var image = document.getElementById('image');
image.src = data;
};
reader.readAsBinaryString(blob);
}
I'm using the image of a red dot that I found on this topic: https://stackoverflow.com/a/4478878/1464608 And the Base64 class is from here: https://stackoverflow.com/a/246813/1464608
But the base64 outcome I get doesn't match and Firefox retrieves me an error of the image being corrupted.
I know this ain't much informations but I don't have a clue where to look :/ Any help is more than welcome!!
You may write it much simpler:
Thanks to the other answers, I managed to receive a jpeg image by websocket and display it in a new window :
Thanks, it's working great!!
So I figure I'd share my final javascript code:
don't really understand why the blob version is so tricky but this did the trick!
Another alternative
I think the cleanest solution would be to change the base64 encoder to operate directly on a Uint8Array instead of a string.
Important: You'll need to set the binaryType of the web socket to "arraybuffer" for this.
The onmessage method should look like this:
The converted encoder should then look like this (based on https://stackoverflow.com/a/246813/1464608):