1

I am converting image data held in an arrayBuffer into a string and then base64 encoding it using the following:

var base64EncodedImage = arrayBufferToBase64(response);

arrayBufferToBase64 = function(buffer) {
  var binary = '';
  var bytes = new Uint8Array( buffer );
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
     binary += String.fromCharCode( bytes[ i ] );
  }
 return window.btoa(binary);
}

When I try to add this data to the src attribute of an image tag

this.imageTag.src = 'data:image/jpeg;base64,' + base64EncodedImage;

..it doesn't display the image, due, I assume to some error in the base64 encoding. When I examine the encodedData, at around character 5000 there is an ellipsis (…) which I assume is what's causing the problems. What is the btoa function doing here and how can I fix it? Is it due to bad data in the arrayBuffer or am I doing something wrong in the binary conversion?

Simple Simon
  • 712
  • 2
  • 8
  • 23
  • *"at around character 5000 there is an ellipsis (…) which I assume is what's causing the problems"* I doubt it, that's more likely an artifact of how you're looking at the string, not actual string content. It's *dramatically* more likely that the problem isn't `btoa`, but rather the code producing the response you're feeding into your `arrayBufferToBase64` function or the `arrayBufferToBase64` function itself. (Remember: [`select` isn't broken](https://pragprog.com/the-pragmatic-programmer/extracts/tips).) – T.J. Crowder Aug 14 '15 at 12:07
  • @T.J.Crowder: Looks like you're right. It was a copy paste artifact from the chrome dev console. I wonder if the problem is that my base64 data is too long in this instance. It's running to 800,000 characters and I imagine that doesn't make most browsers happy! – Simple Simon Aug 14 '15 at 12:46
  • :-) Probably: http://stackoverflow.com/questions/12637395/what-is-the-size-limit-of-a-base64-dataurl-image – T.J. Crowder Aug 14 '15 at 13:03

0 Answers0