865 views
asked in Laravel by
Laravel Webcam Capture Image and Save from Webcam & display with PostgreSQL Database

1 Answer

answered by

Laravel Webcam Capture Image and Save from Webcam & display with PostgreSQL Database

Step 1: Install Laravel

composer create-project --prefer-dist laravel/laravel webcam-app

Step 2: Create Controller

php artisan make:controller WebcamController

Step 2: Create Route

//routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\WebcamController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

  
Route::get('webcam', [WebcamController::class, 'index']);
Route::post('webcam', [WebcamController::class, 'store'])->name('webcam.capture');
Route::get('photo/{id}', [WebcamController::class, 'photo']);

Step 3: Configuration PostgreSQL database in .env file

//.env

DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=webcam_app
DB_USERNAME=postgres
DB_PASSWORD=admin@123

Step 4: Create database with the name of webcam_app in postgresql using PgAdmin.

Step 5: Update Migration and Model

In this step, we will add the "photo" column in the user's table and model.

//database/migrations/xxxxxxx_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('photo_name');
            $table->rememberToken();
            $table->timestamps();
        });
    }
  

    /**
     * Reverse the migrations.

     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Step 6: Execute the migration by using the following command.

php artisan migrate

Step 7: Update the User model.

//app/Models/User.php

<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
  

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
     

    protected $fillable = [
        'name',
        'email',
        'password',
        'photo_name',
    ];
  

    protected $hidden = [
        'password',
        'remember_token',
    ];

  

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    

}

Step 8: Start create method in Controller.

//app/Http/Controllers/WebcamController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Hash;
  

class WebcamController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('webcam');
    }
  

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        // Capture and upload image code
        $img = $request->image;
        $folderPath = "public/";
        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $rand_code = Str::random(6);
        $fileName = time() . $rand_code . '.png';
        $file = $folderPath . $fileName;
        Storage::put($file, $image_base64);

        $id = User::create([
            'name'  =>  $request->name,
            'email' =>  $request->email,
            'password' => Hash::make($request->password),
            'photo_name' => $fileName
        ])->id;

        return redirect('photo/'.$id);
    }


    public function photo($id)
    {
        $data = User::where('id',$id)->first();
        return view('photo',compact('data'));
    }

}

Step 9: Create View File

//resources/view/webcam.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel webcam capture image and save from camera - Chirags.in</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.25/webcam.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <style type="text/css">
        #results { width: 250px;height: 190px; border:1px solid; background:#ccc; }
    </style>
</head>
<body>

<div class="container">
    <h1 class="text-center">Laravel webcam capture image and save from camera - Chirags.in</h1>

    <form method="POST" action="{{ route('webcam.capture') }}">
        @csrf
        <div class="row">
            <div class="col-md-6">
                <input type="text" name="name" class="form-control" placeholder="Name" /> <br/>
				<input type="text" name="email" class="form-control" placeholder="Email Address" /><br/>
				<input type="password" name="password" class="form-control" placeholder="Password" /><br/>
            	<input type="button" class="btn btn-sm btn-primary" id="open_camera" value ="Open Camera"><br/>
                <div id="my_camera" class="d-none"></div>
                <br/>
                <input type="button" id="take_snap" value="Take Snapshot" onClick="take_snapshot()" class="d-none btn btn-info btn-sm" >
                <input type="hidden" name="image" class="image-tag">
            </div>
            <div class="col-md-6">
                <div id="results"></div>
            </div>
            <div class="col-md-12 text-center">
                <br/>
                <button class="btn btn-success">Submit</button>
            </div>
        </div>
    </form>
</div>

<script language="JavaScript">
    $("#open_camera").click(function() {
        $("#my_camera").removeClass('d-none');
        $("#take_snap").removeClass('d-none');

        Webcam.set({
            width: 250,
            height: 190,
            image_format: 'jpeg',
            jpeg_quality: 90
        });
        Webcam.attach('#my_camera');
    });

    function take_snapshot() {
        $("#my_camera").addClass('d-none');
        $("#take_snap").addClass('d-none');
        Webcam.snap( function(data_uri) {
            $(".image-tag").val(data_uri);
            document.getElementById('results').innerHTML = '<img src="'+data_uri+'"/>';
        } );
    }
</script>

</body>
</html>

Step 10: Create View File for display Photo

//resources/view/photo.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel webcam capture image and save from camera - Chirags.in</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>

<div class="container">
    <h1 class="text-center">Laravel webcam Display Photo - Chirags.in</h1>
    <div class="row">
        <div class="col-md-6">
            <p>Name : {{ $data->name }}</p>
            <p>Name : {{ $data->email }}</p>
        </div>
        <div class="col-md-6">
            <picture>
                <img src="{{ asset('storage/'.$data->photo_name) }}" class="img-fluid img-thumbnail" alt="User's image">
            </picture>
        </div>
    </div>
</div>

</body>
</html>

Step 11: Create Storage Link

php artisan storage:link

Note : if you are getting error then you can do the below process.

PS D:\LaravelProject\webcam-app> php artisan storage:link
   ERROR  The [D:\LaravelProject\webcam-app\public\storage] link already exists.

PS D:\LaravelProject\webcam-app> cd .\public\
PS D:\LaravelProject\webcam-app\public> del .\storage\
Confirm
The item at D:\LaravelProject\webcam-app\public\storage\ has children and the Recurse parameter was not specified. 
If you continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

PS D:\LaravelProject\webcam-app> php artisan optimize:clear
  INFO  Clearing cached bootstrap files.
  events ................................................................................................. 3ms DONE  
  views ................................................................................................. 30ms DONE
  cache .................................................................................................. 6ms DONE  
  route .................................................................................................. 3ms DONE
  config ................................................................................................. 1ms DONE  
  compiled ............................................................................................... 3ms DONE  

PS D:\LaravelProject\webcam-app> php artisan storage:link  
	INFO  The [D:\LaravelProject\webcam-app\public\storage] link has been connected to [D:\LaravelProject\webcam-app\storage\app/public].

Step 12: Run Laravel App

php artisan serve

Step 13: Test Application

http://localhost:8000/webcam

Download Code

...