Backend Development 8 min read

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:

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

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:

<code>composer require topthink/think-image</code>

With the plugin installed you can start building the upload page.

HTML markup for the upload form

<code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;{$site.company} Member Management System&lt;/title&gt;
    &lt;link rel="stylesheet" href="layui/css/layui.css"&gt;
    &lt;link rel="stylesheet" href="/css/main.css"&gt;
    &lt;script src="layui/layui.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;
        &lt;label&gt;Photo Upload&lt;/label&gt;
        &lt;input type="text" name="face" id="face" placeholder="Please upload a photo"&gt;
        &lt;button type="button" id="face1"&gt;Upload Photo&lt;/button&gt;
        &lt;img src="/images/thumb.png" id="face_show" width="100px"&gt;
        &lt;p id="faceText"&gt;&lt;/p&gt;
        &lt;input type="button" lay-submit lay-filter="add" value="Submit"&gt;
    &lt;/div&gt;
    &lt;script type="text/javascript"&gt;
        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;
            });
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>

PHP controller for handling the uploaded file

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

Watermark utility class

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

Backend processing to apply watermarks after upload

<code>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'];
    }
}</code>

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.

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

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.