Blog Detail

  • Home
  • Webcam in Angular

Webcam in Angular

In this blog I posted the steps for integrate the web cam in angular. To integrate first you should install ngx-webcam.

npm i ngx-webcam

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import {WebcamModule} from 'ngx-webcam';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    WebcamModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div class="camera-container">
  <webcam [height]="500" [width]="500" [trigger]="triggerObservable" (imageCapture)="handleImage($event)"
          (initError)="handleInitError($event)"></webcam>
  
  <button class="actionBtn" (click)="triggerSnapshot();">Take A Snapshot</button>
</div>

<div class="img-list">
  <div *ngFor="let imgItem of images; let i=index;">
    <img [src]="'data:image/jpg;base64,'+imgItem">
  </div>
</div>

app.component.css

.actionBtn{
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    border-radius: 100px;
    align-self: center;
    margin: 10px;
}

.camera-container{
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    background: black;
    padding: 25px;
}

.img-list{
    display: flex;
    overflow: auto;
    width: 100%;
}

.img-list div{
    width: 150px;
    height: 150px;
    margin: 10px;
}

.img-list img{
    width: 100%;
}

app.component.ts

import { Component } from '@angular/core';
import { WebcamImage, WebcamInitError, WebcamUtil } from 'ngx-webcam';
import { Observable, Subject } from 'rxjs';

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

  public errors: WebcamInitError[] = [];

  // webcam snapshot trigger
  private trigger: Subject<void> = new Subject<void>();

  images:Array<any>;

  public ngOnInit(): void {
    this.images = new Array();
  }

  public triggerSnapshot(): void {
    this.trigger.next();
  }
  public handleInitError(error: WebcamInitError): void {
    this.errors.push(error);
  }

  public handleImage(webcamImage: WebcamImage): void {
    console.info('received webcam image', webcamImage.imageAsBase64);
    this.images.push(webcamImage.imageAsBase64);
  }

  public get triggerObservable(): Observable<void> {
    return this.trigger.asObservable();
  }

}

Write a comment