Overview

Welcome to this comprehensive guide on using TypeScript to determine the two most common colors in an image! If you’ve ever wanted to analyze the colors in an image but didn’t know where to start, then this guide is for you.

Throughout this guide, we’ll walk you through the entire process of loading an image, accessing the pixel data, counting the occurrences of each color, sorting the colors, and finally returning the two most common colors. We’ll provide clear explanations and examples at each step to make it easy to follow along.

I have decided to use show this example in TypeScript because it gives more information about the types of data that are being used. However, if you’re more comfortable with JavaScript, you can use the same concepts and apply them to your code.

Prerequisites

Basic Knowledge of TypeScript/JavaScript

This guide assumes that you have a basic understanding of TypeScript or JavaScript. If you’re new to TypeScript (or want to learn more about it), you can check out our TypeScript Crash Course to get started.

A Code/Text Editor

You’ll need a code/text editor to follow along with this guide. If you don’t have one, I like using Microsoft’s Visual Studio Code, you can download Visual Studio Code for free.

Loading the Image

To load an image in HTML, you can use an element with the accept attribute set to “image/*”. This will allow the user to select an image file from their computer. Here is an example of how you might set this up:

<form>
  <label for="image-input">Select an image:</label>
  <input type="file" id="image-input" accept="image/*" />
</form>

Additionally, We need to add 2 divs to display the image and the most common colors.

<div id="color-1"></div>
<div id="color-2"></div>

Once the user selects an image, you can access the image data using the FileReader API. Here is an example of how you might set this up:

// Get the file input element
const fileInput = document.getElementById("image-input") as HTMLInputElement;

// Add an event listener to the file input element
fileInput.addEventListener("change", (event) => {
  // Get the file from the event
  const file = (event.target as HTMLInputElement).files[0];

  // Create a new FileReader
  const reader = new FileReader();

  // Add an event listener to the FileReader, so that when the image is loaded, we can access the image data
  reader.addEventListener("load", (event) => {
    // Get the image data from the event
    const imageData = event.target.result;
  });

  // Read the image file as a data URL
  reader.readAsDataURL(file);

  // Now lets pass the image data to the getMostCommonColors function, which we'll define later
   const result = getMostCommonColors(imageData);

});
}

Accessing the Pixel Data

Now define the getMostCommonColors function.

async function getMostCommonColors(
  image: HTMLImageElement
): Promise<[string, string]> {
  // Create a canvas element and draw the image onto it
  const canvas = document.createElement("canvas");
  canvas.width = image.width;
  canvas.height = image.height;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(image, 0, 0);

  // Get the pixel data from the canvas
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const pixelData = imageData.data;

  // Create a map to store the color counts
  const colorCounts: Map<string, number> = new Map();

  // Iterate through the pixel data and count the occurrences of each color
  for (let i = 0; i < pixelData.length; i += 4) {
    // Extract the red, green, and blue components of the pixel
    const r = pixelData[i];
    const g = pixelData[i + 1];
    const b = pixelData[i + 2];

    // Create a string representation of the color in the format "rgb(r, g, b)"
    const color = `rgb(${r}, ${g}, ${b})`;

    // Increment the count for the color
    const count = colorCounts.get(color) || 0;
    colorCounts.set(color, count + 1);
  }

  // Sort the colors by their count in descending order
  const sortedColors = Array.from(colorCounts.entries()).sort(
    ([, count1], [, count2]) => count2 - count1
  );

  // Return the two most common colors
  return [sortedColors[0][0], sortedColors[1][0]];
}

Displaying the Most Common Colors

Now that we have the two most common colors, we can display them on the page. To do this, we’ll set the background color of the color divs to the two most common colors.

// Get the color divs
const color1Div = document.getElementById("color-1");
const color2Div = document.getElementById("color-2");

// Set the background color of the color divs to the two most common colors
color1Div.style.backgroundColor = result[0];
color2Div.style.backgroundColor = result[1];

Conclusion

In this guide, we learned how to use TypeScript to determine the two most common colors in an image. We started by loading the image using an <input type="file"> element, then we accessed the pixel data using the canvas API, and finally we displayed the two most common colors on the page.

Thank you for reading this guide about using TypeScript to determine the two most common colors in an image. We hope you found it useful and learned something new!