How To Remove Selected Color From Image Without Any API Or Plugin In Angular

Introduction

In this tutorial, we will learn how to remove the specific color from photos in Angular without any API or Plugin

Let’s get started.

Step 1: make a new angular project

Step 2: Now, open the app component and copy the code below into app.component.html.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="./script.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
        crossorigin="anonymous"></script>
    <title>Document</title>
</head>

<body>

    <div class="container mt-5">
        <div class="SelectIamge">
            <div class="mb-3">
                <label for="formFile" class="form-label fw-bold">select File:</label>
                <input class="form-control" (change)="CreateImageUrl($event)" type="file" id="ImageUpload">
            </div>
            <img class="ProfileImg"
                onerror="this.src = 'https:/www.unityhighschool.org/wp-content/uploads/2014/08/default-placeholder.png'"
                [src]="this.getSantizeUrl(ImgUrl)">
        </div>
        <div class="mt-3">
            <div class="mb-3">
                <label for="formFile" class="form-label fw-bold">Select colour to remove:</label>
                <input class="form-control" id="color_pick" type="color">
            </div>
            <div>
                <button class="btn btn-primary" (click)="removeBackgroung()">Remove Backgroung</button>
            </div>
        </div>
        <div class="mt-5 col-md-8">

            <img (src)="removeBackgroungImage" id="image" alt="">
            <canvas id='canvas'></canvas>
        </div>
    </div>
</body>

</html>

Step 3: Now, open the app.Component.ts file and put the code below into it.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'RemoveBackgroungUI';

  ngOnInit() {
    // this.removeBackgroung();
  }

  constructor(private sanitizer: DomSanitizer) {}

  public removeBackgroungImage: any;
  public ImgUrl: any;

  CreateImageUrl(event: any) {
    debugger;
    var CurruntElement = event.currentTarget;
    this.ImgUrl = URL.createObjectURL(CurruntElement.files[0]);
  }

  public getSantizeUrl(url: string) {
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
  removeBackgroung() {
    const canvas: any = document.getElementById('canvas');
    var ctx = canvas?.getContext('2d');
    var UploadedImg: any = document.getElementById('ImageUpload');
    var image = new Image();
    image.crossOrigin = 'Anonymous';
    image.src = this.ImgUrl;

    var selectedcolor: any = document.getElementById('color_pick');
    var Color = this.hexToRgbA(selectedcolor.value);
    var colorArray = Color.replace('rgba(', '').replace(')', '').split(',');

    image.onload = () => {
      canvas.height = image.height;
      canvas.width = image.width;
      ctx.drawImage(image, 0, 0);
      var imgd = ctx.getImageData(0, 0, image.width, image.height),
        pix = imgd.data,
        newColor = {
          r: 0,
          g: 0,
          b: 0,
          a: 0,
        };

      for (let i = 0, n = pix.length; i < n; i += 4) {
        var r = pix[i],
          g = pix[i + 1],
          b = pix[i + 2];
        if (r == colorArray[0] && g == colorArray[1] && b == colorArray[2]) {
          pix[i] = newColor.r;
          pix[i + 1] = newColor.g;
          pix[i + 2] = newColor.b;
          // pix[i + 3] = newColor.a;
        }
      }
      ctx.putImageData(imgd, 0, 0);
      this.removeBackgroungImage = imgd;
    };
  }

  hexToRgbA(hex: any) {
    var c: any;
    if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
      c = hex.substring(1).split('');
      if (c.length == 3) {
        c = [c[0], c[0], c[1], c[1], c[2], c[2]];
      }
      c = '0x' + c.join('');
      return (
        'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',1)'
      );
    }
    throw new Error('Bad Hex');
  }

}

Step 4: To app.component.css, add the following CSS.

.ProfileImg {
  height: 100px;
  width: 100px;
  border-radius: 20%;
}

.SelectIamge {
  display: grid;
  grid-auto-columns: auto;
  grid-template-columns: 90% 20%;
  grid-gap: 2rem;
}

#canvas{
    height: 35rem;
    width: 80rem;
}

That’s It

When you launch your Angular project, you should see something like this:

Output:

Now follow the following step to remove the color from the image:

Here we replace the selected color with a back color you can choose as per your need.

you can set that color from our app.component.ts file

Thank You!

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories