Backend Development 9 min read

Using PHP and JavaScript to Capture Camera Images with Real-Time Filters

This tutorial explains how to install required components, create a web page that previews the webcam using getUserMedia, send captured frames to a PHP backend, and apply real‑time filter effects with the PHP‑GD library.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP and JavaScript to Capture Camera Images with Real-Time Filters

Photography technology continuously 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 capturing images with a camera and applying desired filters.

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. On Ubuntu, run:

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

2. Create a Camera Real‑Time Preview Page

Next, create a PHP page that displays a live preview of the webcam. The following HTML/JavaScript code sets up a video element, draws frames onto a canvas, converts them to a Base64 JPEG, and shows the result in an img element.

<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>

This code uses the getUserMedia API to access the camera, draws each frame onto a canvas, and updates the preview image with a Base64‑encoded JPEG.

3. Add Real‑Time Filter Effects

After achieving live preview, add a filter selection box and send the chosen filter along with the image data to the PHP backend for processing using the PHP‑GD library.

First, modify the preview page to include a select element for filters:

<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 code for camera preview ...
        document.getElementById('filter').addEventListener('change', function() {
            var filter = this.value;
            var imgData = canvasElem.toDataURL('image/jpeg');
            // Send imgData and filter to server‑side PHP for processing
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>

The JavaScript now captures the selected filter and image data, then sends them via an XMLHttpRequest POST request to a PHP script (e.g., filter.php ).

<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) + '&amp;imgData=' + encodeURIComponent(imgData);
    xhr.send(data);
});
</code>

On the server side, filter.php receives the Base64 image and filter name, creates a GD image resource, applies the selected filter, and returns the processed JPEG:

<code>&lt;?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);
    // Clean up resources
    imagedestroy($imgResource);
}
?&gt;
</code>

This PHP script uses the GD library to apply grayscale, sepia, or invert effects based on the filter value sent from the client.

Finally, update the preview page’s JavaScript to send the image data and selected filter to filter.php , receive the processed image, and display it in the preview element.

By opening the page in a browser, you can select different filters and see the live preview change. When you capture a photo, the PHP backend applies the chosen filter and returns the final image.

This simple quick‑start guide demonstrates how to combine PHP‑GD and Video4Linux with front‑end JavaScript to capture webcam images and add real‑time filter effects, providing a foundation for further creative extensions.

javascriptweb developmentPHPWebcamGD 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.