Convert an image to base64 - Javascript

0

How do I do a function similar to the following, but in Javascript?

// PHP file
<?php 
$path = 'images/imagen.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

something like:

// JS file
convertirImagen(url){
  ...
  return url;
};
console.log(convertirImagen('images/imagen.png')); // base 64 de imagen

The idea is just to pass a parameter and to return the string in base64 to use it in this way:

var imagen = document.getElementById('miimagen');
imagen.setAttribute('src', convertirImagen('images/imagen.png');

I saw this option before but I do not understand the use of callback and I'm looking for a way to simplify it

function imgToBase64(url, callback) {
    if (!window.FileReader) {
      callback(null);
      return;
    }
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
            var reader = new FileReader();
            reader.onloadend = function() {
                callback(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.send();
    }
    
asked by Sebastian Gutierrez 27.07.2017 в 00:02
source

2 answers

1

You can use a canvas, draw it through the image you want and get the base64 code you want

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL();
  return dataURL;
}

var base64 = getBase64Image(document.getElementById("img"));
console.log(base64);
<img id="img" src="http://static.13.cl/7/sites/all/themes/portal/resources/images/logo_13cl-2x.png">

Note: This code will not work in snippet due to security issues towards the image.

    
answered by 27.07.2017 в 00:23
0

Using FileReader

  • Create a new FileReader fileReader .
  • An event of type load is added to fileReader that will be executed once the image is loaded, from which we can extract the image in base64 , accessing property fileReader.result .
  • It uses a callback because FileReader is asynchronous, so you have to pass a function to it, which will be called once you finish loading the image.

  • Finally we tell fileReader to read the image as a data url, through the method readAsDataURL(img) , file must be an object of type File .

  • /*
    * @param { img }: File
    * @param { callback }: function 
    */
    function getBase64FomFile(img, callback){
      let fileReader = new FileReader();
      fileReader.addEventListener('load' function(evt){
        callback(fileReader.result);
      });
      fileReader.readAsDataURL(img);
    }
    
    /* Seria usada de la siguiente manera */
    getBase64FromFile(file, function(base64){
      console.log(base64)
    });

    Note: The snippet will not work

        
    answered by 10.08.2017 в 17:52