Check the predominant color in the image

1

I have the following code that I will put below, which is responsible for picking up the image from which the user places. In this case, the variable img returns me only the url of the image. I wanted to get the image and see what color predominates in it.

Follow the code:

<input type="file" accept='image/*' name="imagem" id="img">
<button id="carregar" onclick="carrega()">Carregar</button>

<script type="text/javascript">
function carrega() {
    var img = $('#img').val();
    alert(img);
    console.log('Img: '+img);
}
</script>
    
asked by anonymous 17.05.2018 / 03:08

1 answer

2

While it is not possible to demonstrate the functionality here in the snippet, you can identify the predominant color of an image using the Color Thief . It is important that the image to be checked is rendered on the page, but if you do not want to display it, just use a display:none in css.

$(document).ready(function() {

  //Carrega a imagem selecionada na <img id="imagem">
  function readURL(input) {

    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function(e) {
        $('#imagem').attr('src', e.target.result);
      }

      reader.readAsDataURL(input.files[0]);
    }
  }

  $("#inputImg").change(function() {
    readURL(this);
  });

  //Captura a cor predominante do elemento <img id="imagem">
  $("#capturar").on('click', function() {  
    var colorThief = new ColorThief();
    var sourceImage = document.getElementById("imagem");
    var color = colorThief.getColor(sourceImage);
    console.clear();
    console.log(color);
    $("#cor").css('background-color', "rgb(" + color + ")");
  });
});
#imagem {
  display: none;
}

#cor {
  width: 50px;
  height: 50px;
  display: block;
}
<!doctype html>
<html class="no-js" lang="en">

<head>
  <script src="http://lokeshdhakar.com/projects/color-thief/js/color-thief.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <input type="file" accept='image/*' id="inputImg">
  <br>
  <img id="imagem" src="" width="50%" style="" />
  <br>
  <button id="capturar">Capturar</button>
  <div id="cor"></div>
</body>

</html>
    
21.05.2018 / 14:38