Backend Development 8 min read

How to Use PHP and JavaScript to Capture Camera Video and Apply Real-Time Filters

This tutorial explains how to install PHP‑GD and Video4Linux, create a web page that streams webcam video with getUserMedia, capture frames to a canvas, send them to a PHP script, and apply real‑time filters such as grayscale, sepia, or invert using the GD library.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP and JavaScript to Capture Camera Video and Apply Real-Time Filters

Photography technology constantly evolves, and you can now use PHP to access a webcam and add real‑time filter effects to your photos; this guide provides a quick‑start tutorial for doing so.

1. Install required components and libraries

First, install the necessary components: the PHP‑GD library for image processing and Video4Linux for video capture on Linux.

sudo apt-get install php-gd
sudo apt-get install v4l-utils

2. Create a camera preview page

Create an HTML page that uses JavaScript’s getUserMedia API to access the webcam, draws the video frames onto a canvas, converts the canvas to a Base64‑encoded JPEG, and displays it in an <img> element.

<!DOCTYPE html>
<html>
<head>
    <title>Camera Preview</title>
</head>
<body>
    <h1>Camera Preview</h1>
    <img id="preview" src="" width="640" height="480" />
    <script>
        var videoElem = document.createElement('video');
        var canvasElem = document.createElement('canvas');
        var context = canvasElem.getContext('2d');
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(function(stream) {
                videoElem.srcObject = stream;
                videoElem.play();
                setInterval(function() {
                    context.drawImage(videoElem, 0, 0, canvasElem.width, canvasElem.height);
                    var imgData = canvasElem.toDataURL('image/jpeg');
                    document.getElementById('preview').src = imgData;
                }, 1000);
            }).catch(function(error) {
                console.log('Error: ' + error.message);
            });
    </script>
</body>
</html>

The script captures a frame every second, converts it to a data URL, and updates the preview image.

3. Add real‑time filter effects

Introduce a <select> element for filter selection and use the PHP‑GD library on the server to apply the chosen filter (none, grayscale, sepia, invert) to the captured image.

<!DOCTYPE html>
<html>
<head>
    <title>Camera Preview with Filters</title>
</head>
<body>
    <h1>Camera Preview with Filters</h1>
    <img id="preview" src="" width="640" height="480" />
    <select id="filter">
        <option value="none">None</option>
        <option value="grayscale">Grayscale</option>
        <option value="sepia">Sepia</option>
        <option value="invert">Invert</option>
    </select>
    <script>
        // ... JavaScript code for camera preview ...
        document.getElementById('filter').addEventListener('change', function() {
            var filter = this.value;
            var imgData = canvasElem.toDataURL('image/jpeg');
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'filter.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById('preview').src = 'data:image/jpeg;base64,' + xhr.responseText;
                }
            };
            var data = 'filter=' + encodeURIComponent(filter) + '&imgData=' + encodeURIComponent(imgData);
            xhr.send(data);
        });
    </script>
</body>
</html>

The JavaScript sends the selected filter and the captured image data to a PHP script via an XMLHttpRequest POST request.

Server‑side PHP filter processing

<?php
// Process the image based on the selected filter
if (isset($_POST['filter']) && isset($_POST['imgData'])) {
    $imgData = $_POST['imgData'];
    $filter = $_POST['filter'];
    // Create GD image resource from Base64 image data
    $imgResource = imagecreatefromstring(base64_decode(str_replace('data:image/jpeg;base64,', '', $imgData)));
    // Apply filters based on the selected option
    switch ($filter) {
        case 'none':
            break;
        case 'grayscale':
            imagefilter($imgResource, IMG_FILTER_GRAYSCALE);
            break;
        case 'sepia':
            imagefilter($imgResource, IMG_FILTER_GRAYSCALE);
            imagefilter($imgResource, IMG_FILTER_COLORIZE, 90, 60, 40);
            break;
        case 'invert':
            imagefilter($imgResource, IMG_FILTER_NEGATE);
            break;
    }
    // Output the filtered image
    header('Content-Type: image/jpeg');
    imagejpeg($imgResource);
    imagedestroy($imgResource);
}
?>

This PHP code decodes the Base64 image, applies the selected GD filter, and returns the processed JPEG.

After updating the preview page’s JavaScript to send the data, you can open the page in a browser, select different filters, and see the real‑time effect on the captured image; clicking a capture button would let the PHP code output the filtered photo.

The guide provides a simple yet functional starting point for using PHP‑GD and Video4Linux to capture webcam images and apply creative filter effects.

JavaScriptPHPWebcamGD Libraryrealtime-filtervideofourlinux
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.