Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Binary form to base64 string in javascript [duplicate]

Tags:

I am querying salesforce for some attachment data and it returns the data in binary format.

enter image description here

I have tried to convert the same to base64, but I have been quite unsuccessful so far. I have tried the btoa() method but it returns the The string to be encoded contains characters outside of the Latin1 range. error.

I tried to use the fileReader method i.e., readAsDataURL(), it returns the base64 string but unfortunately that doesn't represent the image.

COuld you please help me out as to how to convert the binary form of the data to base64encoded string?

Edit Ultimately, I want to show the image on the webpage with the data I am getting which I am unable to do

like image 647
Sam Avatar asked May 19 '16 14:05

Sam


1 Answers

If you are retrieving that image from server, you have the choice of convert to base64 from the server (and serve it ready to the client), or you need to pass the URL of the image from server, and then read it and convert to base64 from client javascript. But if you retrieve that binary from server to client, client will be unable to parse it since the data is corrupted due the wrong sending method.

Example converting a URL to base64 (with Canvas or FileReader):

function convertImgToDataURLviaCanvas(url){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL("image/png");
        canvas = null; 
    };
    img.src = url;
}

function convertFileToDataURLviaFileReader(url){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            console.log(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

Conversion Fiddle:

http://jsfiddle.net/handtrix/yvq5y/

like image 127
Marcos Pérez Gude Avatar answered Sep 28 '22 01:09

Marcos Pérez Gude