Home Backend Development PHP Tutorial How to implement the function of randomly generating watermark images in PHP

How to implement the function of randomly generating watermark images in PHP

May 24, 2018 pm 04:31 PM
php picture watermark

This article mainly introduces the relevant information of PHP to generate random watermark images in detail. It has certain reference value. Interested friends can refer to

GD graphics library based on PHP. Generate an image. Only for those who are new to the GD library and can learn from examples.

1. Requirements

The layout of the website uses a style similar to the MOOC course list. Each course is a banner picture, and below the picture is the title and introduction. Because there are a large number of courses, there are no special banners designed for all courses, so you need to generate images yourself according to certain rules (I originally planned to use p layout to solve the problem, but p img is not well controlled in responsive layout).

Generated renderings:

2. Tools & Materials

1. Open PHP GD graphics library extension
2. Prepare multiple small watermark images
3. Get the background color RGB value of the pre-generated image

3. Code

The process of generating images is detailed in the code.

class GenerateRandomImage
{
  /** @var integer 图片宽度 */
  public $imgWidth = 272;
  /** @var integer 图片高度 */
  public $imgHeight = 162;
  /** @var 根据type不同来生成不同的背景颜色,目前留个type分别为蓝色、紫色、黄色、绿色、灰色、土黄色 */
  public $type = '';
  /** @var 图片上要显示的文字 */
  public $text = '';
  /** @var integer 图片上文字的字体大小 */
  public $fontSize = 16;

  public function __construct($type, $text)
  {
    $this->type = $type;
    $this->text = $text;
  }
  /**
   * 创建生成随机图片
   * @author bignerd
   * @since 2017-03-21T14:49:41+0800
   */
  public function createImg()
  {
    /** @var 创建一个指定图片大小的空调色板
    $image = imagecreate($this->imgWidth, $this->imgHeight);
    $rgb  = $this->getBackground($this->type);
    /** @var 为图片创建一个背景色 */
    $backgroundColor = imagecolorallocate($image, $rgb['r'], $rgb['g'], $rgb['b']);
    /** @var 创建文字白色字体 */
    $textColor = imagecolorallocate($image, 255, 255, 255);
    /** @var 字体文件路径 */
    $font = $_SERVER['DOCUMENT_ROOT'].'/public/font/simhei.ttf';

    $x = 18;//文字起始位置x坐标
    $y = 50;//文字起始位置y坐标
    /** 文字写入图片 */
    $angle = 0;//角度0
    imagettftext($image, $this->fontSize, $angle, $x, $y, $textColor, $font, $this->text);
    /** @var 水印图片路径 **/
    $waterImgPath = $this->randWaterImage();
    /** @var 获取图片信息,返回值$waterInfo[2] 为图片类型常量 */
    $waterInfo  = getimagesize($waterImgPath);
    /** @var 将图片类型常量转换为真正的类型,如png */
    $waterType  = image_type_to_extension($waterInfo[2], false);//获取文件类型

    $createImageFunc = 'imagecreatefrom'.$waterType;
    /** @var 创建一个水印图片的副本 $createImageFunc 为根据图片类型来动态生成预调用的创建图片函数*/
    $mask = $createImageFunc($waterImgPath);
    $posX = $this->imgWidth - $waterInfo[0];//水印图片,在目标图片中的位置的x坐标
    $posY = $this->imgHeight - $waterInfo[1];//水印图片,在目标图片中的位置的y坐标
    /** http请求响应类型设置为 image/png 以便直接显示为图片 */
    header("Content-Type:image/png");
    /** 水印图片复制到创建的image */
    imagecopy($image, $mask, $posX, $posY, 0, 0, $waterInfo[0], $waterInfo[1]);
    imagepng($image);//输入图片到浏览器或者文件
    imagedestroy($image);//销毁图片
  } 
  /**
   * 图片背景颜色的rgb值
   * @author bignerd
   * @since 2017-03-21T14:50:16+0800
   */
  public function getBackground()
  {
    $background = [
      '1'=>['r'=>0, 'g'=>160,'b'=>233],
      '2'=>['r'=>198,'g'=>0, 'b'=>110],
      '3'=>['r'=>237,'g'=>109,'b'=>0],
      '4'=>['r'=>33, 'g'=>148,'b'=>75],
      '5'=>['r'=>63, 'g'=>58, 'b'=>57],      
      '6'=>['r'=>202,'g'=>162,'b'=>101],
    ];
    return $background[$this->type];
  }
  /**
   * 随机水印图片路径
   * @author bignerd
   * @since 2017-03-21T14:51:00+0800
   * @return 路径
   */
  public function randWaterImage()
  {
    $folder = [
      '1'=>'product','2'=>'team','3'=>'architecture','4'=>'developer','5'=>'test','6'=>'engineer'
    ];
    $targetFolder = $_SERVER['DOCUMENT_ROOT'].'/public/images/role/'.$folder[$this->type].'/'.rand(1,38).'.png';
    return $targetFolder;
  }
}

$image = new GenerateRandomImage(1,"扛得住的MySql数据架构");
$image->createImg();
Copy after login

So we can use it directly in the page to display the image directly.

Note: I encountered a problem during the process: if the watermark image is a transparent png image, when you copy the watermark image to image, it will appear as The white background cannot be transparently blended with the image background we set, so the same color processing needs to be done for random watermark images.

4. Summary

This small example uses simple steps to generate an image, which can be displayed directly in the browser, or it can be given to imagepng Add the second parameter, which is the path, to save the image. Therefore, by learning several methods in the GD library in the examples, you can create pictures, add text watermarks, or image watermarks to pictures.

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP implementationPicture watermark class encapsulation

phpCode of picture watermark

PHP implementationPicture watermark class encapsulation code sharing

The above is the detailed content of How to implement the function of randomly generating watermark images in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles