Implementing Image Upload with Automatic Watermark Using PHP, Layui, and Think-Image

This article explains how to set up image uploading with automatic watermarking in a PHP-based management system, covering Composer installation, Think-Image plugin integration, front‑end Layui upload handling, and server‑side code for adding both image and text watermarks.

php Courses
php Courses
php Courses
Implementing Image Upload with Automatic Watermark Using PHP, Layui, and Think-Image

When developing a website management system, many clients require that uploaded photos automatically receive a watermark to prevent unauthorized reuse or infringement. This guide shows how to achieve that using the Layui front‑end framework and the Think-Image library in a PHP (TP5.1) project.

Step 1: Install Composer – Composer is required to manage PHP dependencies. On Linux or macOS run:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

On Windows download and run Composer-Setup.exe, then add Composer to your system path.

Step 2: Install the image processing plugin – After Composer is ready, navigate to your project directory and execute: composer require topthink/think-image With the plugin installed you can start building the upload page.

HTML markup for the upload form

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{$site.company} Member Management System</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <link rel="stylesheet" href="/css/main.css">
    <script src="layui/layui.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <label>Photo Upload</label>
        <input type="text" name="face" id="face" placeholder="Please upload a photo">
        <button type="button" id="face1">Upload Photo</button>
        <img src="/images/thumb.png" id="face_show" width="100px">
        <p id="faceText"></p>
        <input type="button" lay-submit lay-filter="add" value="Submit">
    </div>
    <script type="text/javascript">
        layui.use(['form','layer','upload','element'], function(){
            var $ = layui.jquery;
            var form = layui.form, layer = layui.layer, upload = layui.upload, element = layui.element;
            // Image upload configuration
            var uploadInst = upload.render({
                elem: '#face1',
                url: '{:url("uploadFile")}',
                before: function(obj){
                    obj.preview(function(index, file, result){
                        $('#face_show').attr('src', result); // preview image
                    });
                    element.progress('demo', '0%');
                    layer.msg('Uploading', {icon:16, time:0});
                },
                done: function(res){
                    if(res.code > 0){
                        layer.msg('Upload successful');
                        document.getElementById('face').value = res.path;
                        $('#faceText').html('');
                    }else{
                        layer.msg('Upload failed', {icon:2});
                    }
                },
                error: function(){
                    var demoText = $('#faceText');
                    demoText.html('<span style="color:#FF5722;">Upload failed</span> <a class="layui-btn layui-btn-xs demo-reload">Retry</a>');
                    demoText.find('.demo-reload').on('click', function(){ uploadInst.upload(); });
                },
                progress: function(n){
                    element.progress('demo', n + '%');
                    if(n == 100){ layer.msg('Upload complete', {icon:1}); }
                }
            });
            form.on('submit(add)', function(data){
                $.post('{:url("save")}', $("form").serialize(), function(res){
                    if(res.code == 1){
                        layer.msg(res.msg);
                        setTimeout(function(){ parent.window.location.reload(); }, 1000);
                    }else{
                        layer.alert(res.msg, {icon:6});
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html>

PHP controller for handling the uploaded file

public function uploadFile(){
    // Get uploaded file information
    $file = request()->file('file');
    // Create a subdirectory named by the current date
    $path = date("Ymd");
    // Generate a unique filename using timestamp and random number
    $filename = time().rand(100,1000);
    // Move the file to the target directory
    $info = $file->move('uploadfile/'.$path.'/', $filename);
    if($info){
        $photo1 = '/uploadfile/'.$path.'/'.$info->getSaveName();
        return json(['code'=>1, 'path'=>$photo1]);
    }else{
        return $file->getError();
    }
}

Watermark utility class

namespace app\api\classes;
use think\Image;
class imgWaterClass{
    /** Add text watermark */
    public function imageWaterText($path, $text){
        $img = ".".$path;
        $image = Image::open($img);
        $image->text($text, './static/style/font/simsun.ttc', 20, '#ffffff', 9, '-10px')->save($img);
        return $img;
    }
    /** Add image watermark */
    public function imageWaterImg($path, $logo){
        $img = ".".$path;
        $logo = ".".$logo;
        $image = Image::open($img);
        $image->water($logo, Image::WATER_SOUTHEAST)->save($img);
        return $img;
    }
}

Backend processing to apply watermarks after upload

public function save(){
    $data = Request::param();
    $water = new imgWaterClass();
    $img_url = $data['face']; // original image
    $logo = "/uploads/logo.png"; // watermark image
    $water->imageWaterImg($img_url, $logo); // add image watermark
    $water->imageWaterText($img_url, 'I am watermark'); // add text watermark
    if($img_url){
        return ['code'=>1, 'msg'=>'Save successful'];
    }else{
        return ['code'=>0, 'msg'=>'Save failed'];
    }
}

The provided code snippets demonstrate a complete workflow: installing dependencies, creating the front‑end upload interface with Layui, handling the file upload in PHP, and applying both image and text watermarks using Think-Image. Adapt the paths and styles as needed for your own project.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

image uploadLayuiThink-Image
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

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.