search
HomeBackend DevelopmentPHP TutorialEncapsulation of adding, compressing and cutting PHP image watermarks

 PHP mainly uses the GD library extension to operate image files. When we frequently use PHP to operate images, we will naturally encapsulate many functions, otherwise we will write too much repetitive code. When there are many functions related to pictures, we can consider organizing these functions, so we have the idea of ​​encapsulating them into classes.

 There are four main steps to operating pictures:

  1. Open pictures
  2. Manipulate pictures
  3. Output pictures
  4. Destroy pictures

The three steps 1, 3, and 4 need to be written every time, and they are almost the same every time. The only step that really needs to be changed is the image manipulation step. Manipulating pictures is often done through one or more main GD functions.

This article encapsulates the four methods in the class, text watermark (imagettftext()), image watermark (imagecopymerge()), image compression, image cutting (imagecopyresampled()). The rest of the commonly used GD functions will not be described in detail. Go directly to the code:

<span>php 

</span><span>class</span><span> Image
{    
    </span><span>private</span><span> $info;

    </span><span>private</span><span> $image;
    </span><span>public</span><span> $type;
    </span><span>public</span><span> function __construct($src)
    {

        $</span><span>this</span>->info=<span>getimagesize($src);
        $</span><span>this</span>->type=image_type_to_extension($<span>this</span>->info[<span>'</span><span>2</span><span>'</span>],<span>false</span><span>);
        $fun</span>=<span>"</span><span>imagecreatefrom{$this->type}</span><span>"</span><span>;
        $</span><span>this</span>->image=<span>$fun($src);
    }
    </span><span>/*</span><span>*
     * 文字水印
     * @param  [type]  $font     字体
     * @param  [type]  $content  内容
     * @param  [type]  $size     文字大小
     * @param  [type]  $col      文字颜色(四元数组)
     * @param  array   $location 位置 
     * @param  integer $angle    倾斜角度
     * @return [type]           
     </span><span>*/</span><span>public</span> function fontMark($font,$content,$size,$col,$location,$angle=<span>0</span><span>){
        $col</span>=imagecolorallocatealpha($<span>this</span>->image, $col[<span>'</span><span>0</span><span>'</span>], $col[<span>'</span><span>1</span><span>'</span>], $col[<span>'</span><span>2</span><span>'</span>],$col[<span>'</span><span>3</span><span>'</span><span>]);

        imagettftext($</span><span>this</span>->image, $size, $angle, $location[<span>'</span><span>0</span><span>'</span>], $location[<span>'</span><span>1</span><span>'</span><span>], $col,$font,$content);
    }
    
    </span><span>/*</span><span>*
     * 图片水印
     * @param  [type] $imageMark 水印图片地址
     * @param  [type] $dst       水印图片在原图片中的位置
     * @param  [type] $pct       透明度
     * @return [type]            
     </span><span>*/</span><span>public</span><span> function imageMark($imageMark,$dst,$pct){
        $info2</span>=<span>getimagesize($imageMark);
        $type</span>=image_type_to_extension($info2[<span>'</span><span>2</span><span>'</span>],<span>false</span><span>);
        $func2</span>=<span>"</span><span>imagecreatefrom</span><span>"</span><span>.$type;
        $water</span>=<span>$func2($imageMark);

        imagecopymerge($</span><span>this</span>->image, $water, $dst[<span>0</span>], $dst[<span>1</span>], <span>0</span>, <span>0</span>, $info2[<span>'</span><span>0</span><span>'</span>], $info2[<span>'</span><span>1</span><span>'</span><span>], $pct);
        imagedestroy($water);

    }
    </span><span>/*</span><span>*
     * 压缩图片
     * @param  [type] $thumbSize 压缩图片大小
     * @return [type]            [description]
     </span><span>*/</span><span>public</span><span> function thumb($thumbSize){
        $imageThumb</span>=imagecreatetruecolor($thumbSize[<span>0</span>], $thumbSize[<span>1</span><span>]);
        
        imagecopyresampled($imageThumb, $</span><span>this</span>->image, <span>0</span>, <span>0</span>, <span>0</span>, <span>0</span>, $thumbSize[<span>0</span>], $thumbSize[<span>1</span>], $<span>this</span>->info[<span>'</span><span>0</span><span>'</span>], $<span>this</span>->info[<span>'</span><span>1</span><span>'</span><span>]);
        imagedestroy($</span><span>this</span>-><span>image);
        $</span><span>this</span>->image=<span>$imageThumb;
    }
    </span><span>/*</span><span>*
    * 裁剪图片
     * @param  [type] $cutSize  裁剪大小
     * @param  [type] $location 裁剪位置
     * @return [type]           [description]
     </span><span>*/</span><span>public</span><span> function cut($cutSize,$location){
         $imageCut</span>=imagecreatetruecolor($cutSize[<span>0</span>],$cutSize[<span>1</span><span>]);

         imagecopyresampled($imageCut, $</span><span>this</span>->image, <span>0</span>, <span>0</span>, $location[<span>0</span>], $location[<span>1</span>],$cutSize[<span>0</span>],$cutSize[<span>1</span>],$cutSize[<span>0</span>],$cutSize[<span>1</span><span>]);
         imagedestroy($</span><span>this</span>-><span>image);
         $</span><span>this</span>->image=<span>$imageCut;
     }
    </span><span>/*</span><span>*
     * 展现图片
     * @return [type] [description]
     </span><span>*/</span><span>public</span><span> function show(){
        header(</span><span>"</span><span>content-type:</span><span>"</span>.$<span>this</span>->info[<span>'</span><span>mime</span><span>'</span><span>]);

        $funn</span>=<span>"</span><span>image</span><span>"</span>.$<span>this</span>-><span>type;

        $funn($</span><span>this</span>-><span>image);
    }
    </span><span>/*</span><span>*
     * 保存图片
 * @param  [type] $newname 新图片名
 * @return [type]          [description]
 </span><span>*/</span><span>public</span><span> function save($newname){
         header(</span><span>"</span><span>content-type:</span><span>"</span>.$<span>this</span>->info[<span>'</span><span>mime</span><span>'</span><span>]);

         $funn</span>=<span>"</span><span>image</span><span>"</span>.$<span>this</span>-><span>type;

         $funn($</span><span>this</span>->image,$newname.<span>'</span><span>.</span><span>'</span>.$<span>this</span>-><span>type);
     }
     </span><span>public</span><span> function __destruct(){
         imagedestroy($</span><span>this</span>-><span>image);
     }

 }

 </span>?>

If you need other operations, just add them to this class~~

The above introduces the encapsulation of adding, compressing, and cutting PHP image watermarks, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools