-2

how to convert image file to binary format in Javascript. I can not get a solution for this. Please explain Is this possible or not?

Gokul Kumar
  • 389
  • 6
  • 16
  • 1
    https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – Anthony Astige Jun 27 '16 at 06:33
  • 1
    An image file *is* binary. What exactly do you want to convert? – Bergi Jun 27 '16 at 07:31
  • The dup assumes locally loaded files. The answers are outdated and one doesn't produce binary format (data-uri). OP should consider providing more info though. –  Jul 05 '16 at 20:45

2 Answers2

1

The image file at the moment is a binary image data (png, jpg, gif etc), if your question was directed to ask about conversion to a base64 encoded string then the best way is to use HTML5 canvas for your conversion, below is a given function that can be used at your disposal:

function toDataUrl(url, callback, outputFormat){
    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(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

Then you can call:

toDataUrl(imageURLString, function(base64Img){
    // Base64DataURL
});
zubair1024
  • 843
  • 8
  • 24
1

Load the image using XMLHttpRequest. This will avoid having to go through canvas. CORS restrictions apply to both so the only difference is that with XMLHttpRequest you can load the data directly as ArrayBuffer or a Blob.

// Load image via XMLHttpRequest
var xhr = new XMLHttpRequest();                       // create a "loader"
xhr.open("GET", "https://i.imgur.com/9LqhOl3b.jpg");  // url, CORS apply (!)
xhr.responseType = "arraybuffer";                     // or "blob"
xhr.onerror = alert;                                  // use error handler here
xhr.onload = function() {                             // async onload handler
  if (xhr.status === 200) process(xhr.response);      // All OK
  else alert("Error:" + xhr.statusText);              // oops...
};
xhr.send();                                           // send request

// Now we can access it through typed array wo/ canvas
function process(buffer) {

  var view = new Uint8Array(buffer);                  // access bytes through a view
  console.log("Content:", view[0], view[1], view[2], view[3], ".. etc..");
  
  // convert to blob and show
  var blob = new Blob([view], {type: "image/jpeg"});
  var url = URL.createObjectURL(blob);
  var img = new Image;
  img.src = url;
  document.body.appendChild(img);
}
Loading...<br>