Check the predominant color in the image

Asked

Viewed 1,480 times

2

I have the following code that I will put below, which is responsible for taking the image that the user puts. In this case, the variable img returns only the image url. I wanted to take the image and see which color predominates in the same.

Follows 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>
  • With the image URL, you can send a GET request to get the image itself and then do whatever processing you want on it.

1 answer

4


Although it is not possible to demonstrate how it works here in the snippet, you can identify the predominant color of an image using the library Color Thief. It is important that the image to be checked is rendered on the page, but if you do not want to show 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>
  <script src="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>

  • 1

    It worked! Thank you so much for all your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.