Backend Development 9 min read

How to Build a Real-Time Camera Filter App with PHP and JavaScript

This tutorial walks you through installing PHP‑GD and Video4Linux, creating a web page that previews the webcam using getUserMedia, adding a filter selector, and processing the image on the server with PHP‑GD to apply real‑time visual effects.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Build a Real-Time Camera Filter App with PHP and JavaScript

Photography technology continues to evolve, and you can now use PHP to access a webcam and add real‑time filter effects for more fun.

1. Install required components

Install the PHP‑GD image library and the Video4Linux capture interface on Ubuntu.

<code>sudo apt-get install php-gd
sudo apt-get install v4l-utils</code>

2. Create a camera preview page

Create a simple HTML page that displays the webcam feed. The page includes an

&lt;img id="preview"&gt;

element and JavaScript that uses the

getUserMedia

API to obtain a video stream, draws each frame onto a canvas, converts the canvas to a Base64‑encoded JPEG, and updates the preview image every second.

<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Camera Preview&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Camera Preview&lt;/h1&gt;
    &lt;img id="preview" src="" width="640" height="480" /&gt;
    &lt;script&gt;
        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);
            });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>

The script accesses the camera, draws frames to a canvas, and updates the

&lt;img&gt;

element with a Base64‑encoded JPEG.

3. Add real‑time filter effects

Insert a

&lt;select&gt;

element for filter selection and modify the JavaScript to send the chosen filter and image data to a server‑side PHP script.

<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Camera Preview with Filters&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Camera Preview with Filters&lt;/h1&gt;
    &lt;img id="preview" src="" width="640" height="480" /&gt;
    &lt;select id="filter"&gt;
        &lt;option value="none"&gt;None&lt;/option&gt;
        &lt;option value="grayscale"&gt;Grayscale&lt;/option&gt;
        &lt;option value="sepia"&gt;Sepia&lt;/option&gt;
        &lt;option value="invert"&gt;Invert&lt;/option&gt;
    &lt;/select&gt;
    &lt;script&gt;
        // ... JavaScript 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);
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>

The PHP script receives

$_POST['filter']

and

$_POST['imgData']

, creates a GD image from the Base64 data, applies the selected filter (none, grayscale, sepia, invert) using

imagefilter

, outputs the processed JPEG, and frees resources.

<code>&lt;?php
if (isset($_POST['filter']) && isset($_POST['imgData'])) {
    $imgData = $_POST['imgData'];
    $filter = $_POST['filter'];
    $imgResource = imagecreatefromstring(base64_decode(str_replace('data:image/jpeg;base64,', '', $imgData)));
    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;
    }
    header('Content-Type: image/jpeg');
    imagejpeg($imgResource);
    imagedestroy($imgResource);
}
?&gt;</code>

Update the preview page JavaScript to POST the data to

filter.php

and replace the preview image with the server‑processed result.

<code>// ... 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);
});</code>

Open the page in a browser, choose different filters, and observe the live preview change; when a capture button is added, PHP will apply the selected filter and output the final image.

This quick‑start guide shows how to combine PHP‑GD, Video4Linux, and JavaScript to capture webcam images and apply real‑time filters, providing a solid foundation for further creative extensions.

JavaScriptimage processingPHPWebcamGD LibraryReal-time Filters
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.