


How to implement the function of randomly generating watermark images in PHP
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();
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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,

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

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

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
