How to find average color of an image using JavaScript?


Overview

The extraction of colors from an image means that the colors which are present in an image in the form of pixels will be extracted, and an average of the pixels of the distinct is calculated in the form of RGB (Red Green Blue) and a new average color will be formed on the basis of the average of the color pixels. So we can achieve this with the help of JavaScript, in the JavaScript there is a property "canvas" which is used to draw an image or any content in the form of pixels.

Approach

To build this feature we will be using the canvas method to convert the image into the canvas through which we can manipulate the and access the colors of the image. For this we will be collecting the data of an image by getting the width, height of an original image. For this we will be using the given below Syntax.

Syntax

const canvas = document.createElement("canvas");
const imgCanva = canvas.getContext("2d");
imgCanva.drawImage(imageElement, 0, 0);

So through the draw image method an original image will be drawn on the canvas in the memory. From this canvas we will be extracting the R(Red), G(Green) and B(Blue) pixels from an image and after calculating the average a new RGB color will be formed.

Algorithm

  • Step 1 − Create a HTML file on your text editor and add an HTML boilerplate to the file.

  • Step 2 − Now use the HTML <img> tag to add an image to the file and add an id attribute to it with the name "myImg".

<img id="myImg" src="https://st.depositphotos.com/1420973/3112/i/600/depositphotos_31129547-stock-photo-venice-landmark-burano-island-canal.jpg" crossorigin>
  • Step 3 − Now use the internal styling to style the layout of the page.

<style>
   body {
      display: flex;
      justify-content: center;
      align-items: center;
   }
   img {
      width: 80%;
      height: 20rem;
      border-radius: 8px;
   }
</style>
  • Step 4 − Now create a script tag to the body tag of the page.

<script></script>
  • Step 5 − Create a JavaScript arrow based function with the name as "extractAvgColor" and pass two parameters as "imageElement" which takes the image as input and other is the ratio at which the color ratio will be decided for an average.

extractAvgColor=(imageElement, ratio)=>{}
  • Step 6 − Create an "canvas" element using the createElement() method.

const canvas = document.createElement("canvas");
  • Step 7 − Now convert the image to the canvas element for its manipulation.

const canvas = document.createElement("canvas")

let height = canvas.height = imageElement.naturalHeight
let width = canvas.width = imageElement.naturalWidth

const imgCanva = canvas.getContext("2d")
imgCanva.drawImage(imageElement, 0, 0)

data = context.getImageData(0, 0, width, height)
length = data.data.length
  • Step 8 − Now iterate through the pixels of an image and store the RGB color to their respective variables.

while ((i += ratio * 4) < length) {
   ++count
   R += data.data[i]
   G += data.data[i + 1]
   B += data.data[i + 2]
}
  • Step 9 − Now divide the RGB color from the count.

R = (R / count)
G = (G / count)
B = (B / count)
  • Step 10 − Return the R, G and B value to the function.

return {
   R, G, B
}
  • Step 11 − Use the HTML DOM object to access the image in the body tag using its id name and store it in a variable "img".

const img = document.getElementById("myImg");
  • Step 12 − Now use the onload method with the img to trigger the extractAvgColor().

img.onload = () => {
   const { R, G, B } = extractAvgColor(img, 9999)
   document.body.style.background = `rgb(${R}, ${G},${B})`
}
  • Step 13 − Use the css property to set new average color to the background of an HTML page.

Example

In this Example we will be adding an image on the web page and will find an average color from an image and then the average of the color will be changed in the background of the image.

<html>
<head>
   <title> average color of an image </title>
   <style>
      body {
         display: flex;
         justify-content: center;
         align-items: center;
      }
      img {
         width: 80%;
         height: 20rem;
         border-radius: 8px;
      }
   </style>
</head>
<body>
   <img id="myImg" src="https://st.depositphotos.com/1420973/3112/i/600/depositphotos_31129547-stock-photo-venice-landmark-burano-island-canal.jpg" crossorigin>
   <script>
      extractAvgColor=(imageElement, ratio)=>{

         let data, length, i = 0, count = 0, R = 0, G = 0, B = 0;

         const canvas = document.createElement("canvas")

         let height = canvas.height = imageElement.naturalHeight
         let width = canvas.width = imageElement.naturalWidth

         const imgCanva = canvas.getContext("2d")
         imgCanva.drawImage(imageElement, 0, 0)

         data = context.getImageData(0, 0, width, height)
         length = data.data.length

         while ((i += ratio * 4) < length) {
            ++count

            R += data.data[i]
            G += data.data[i + 1]
            B += data.data[i + 2]
         }

         R = (R / count)
         G = (G / count)
         B = (B / count)

         return {
            R, G, B
         }
      }

      const img = document.getElementById("myImg");

      img.onload = () => {
         const { R, G, B } = extractAvgColor(img, 9999)
         document.body.style.background = `rgb(${R}, ${G},${B})`
      }
   </script>
</body>
</html>

The image below shows the Output of the above feature, which shows an image with the background somewhat similar to the image colors. In this as you can see an image contains multiple colors such as yellow, red, blue and almost all colors. So when this image is converted to the canvas and the RGB pixels are calculated it gives an average of a new color as the background color which is somewhat bluish gray.

Conclusion

In the above program we have used the "onload" method with an image because the background of the image will only be changed when the image will be loaded on the browser window otherwise the background will not be changed. The above feature which we have created is used by most of the modern applications to make a user interface more attractive. Moreover most of the products of YouTube like YouTube music and YouTube player use this feature to synchronize with their music. We can also use this feature to build more attractive image gallery. It is also important to use the "crossorigin" attribute with the image tag as we are loading the image form the different hosted image. We can also make the background color gradient by extracting the color from an image in different ratios.

Updated on: 13-Oct-2023

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements