search
HomeBackend DevelopmentPHP TutorialIntroducing the image processing library GD in PHP

Introducing the image processing library GD in PHP

Jun 23, 2023 am 08:10 AM
phpgd libraryImage Processing

GD is a very practical image processing library in PHP. Using the GD library, PHP developers can easily process, generate and output images, such as generating verification codes, thumbnails, watermarks, etc. This article will introduce the GD library to you and give some examples of using the GD library in PHP.

The GD library is an open source library, originally designed for C language, and can be used to process various image formats such as JPEG, PNG, and GIF. Since PHP 5.0, the GD library can be used with PHP.

Using the GD library, you can:

  • Read and save images
  • Adjust image size
  • Adjust image quality
  • Add text and shapes
  • Add watermark
  • Convert image format, etc.

In PHP, to use the GD library, you need to first check whether the GD extension is installed. You can check by running the following code:

if (extension_loaded('gd') && function_exists('gd_info')) {
    echo 'GD 库已安装';
} else {
    echo 'GD 库未安装';
}

If the output is GD library installed, it means that the GD library extension has been installed normally.

The following are some practical examples of the GD library.

Generate verification code

Generating verification code is a common task in website development, and the GD library easily implements this function. The specific implementation method is as follows:

// 生成验证码
function generateVerificationCode($length = 4) {
    // 验证码字符集,去掉了容易混淆的字符
    $chars = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
    // 洗牌
    $chars = str_shuffle($chars);
    // 取出前 $length 个字符作为验证码
    $code = substr($chars, 0, $length);
    // 存储验证码
    $_SESSION['verificationCode'] = $code;
    // 创建画布
    $image = imagecreatetruecolor(120, 30);
    // 分配颜色
    $bgColor = imagecolorallocate($image, 255, 255, 255);
    $textColor = imagecolorallocate($image, 0, 0, 0);
    // 填充背景
    imagefill($image, 0, 0, $bgColor);
    // 画上验证码
    imagestring($image, 5, 20, 8, $code, $textColor);
    // 输出图像
    header('Content-type: image/jpeg');
    imagejpeg($image);
    // 销毁图像
    imagedestroy($image);
}

In the above code, we first generate a random verification code and then store it in SESSION. Then create a 120x30 pixel canvas, fill the background with white, draw the verification code onto the canvas, and output it in image format.

Generate thumbnails

In websites, in order to speed up page loading, large images are usually compressed into small thumbnails. The following is the implementation method of using the GD library to generate thumbnails:

// 生成缩略图
function generateThumbnail($src, $dst, $width, $height) {
    // 获取原图信息
    list($srcWidth, $srcHeight, $type) = getimagesize($src);
    // 根据原图类型创建画布
    switch ($type) {
        case IMAGETYPE_JPEG:
            $imageSrc = imagecreatefromjpeg($src);
            break;
        case IMAGETYPE_PNG:
            $imageSrc = imagecreatefrompng($src);
            break;
        case IMAGETYPE_GIF:
            $imageSrc = imagecreatefromgif($src);
            break;
        default:
            throw new Exception('不支持的图像类型');
    }
    // 计算缩略图的宽高比
    $ratio = min($width / $srcWidth, $height / $srcHeight);
    // 计算缩略图的实际宽度和高度
    $thumbWidth = intval($srcWidth * $ratio);
    $thumbHeight = intval($srcHeight * $ratio);
    // 创建目标画布
    $imageDst = imagecreatetruecolor($thumbWidth, $thumbHeight);
    // 复制原图到目标画布,并调整大小
    imagecopyresampled($imageDst, $imageSrc, 0, 0, 0, 0, $thumbWidth, 
        $thumbHeight, $srcWidth, $srcHeight);
    // 保存图片到指定路径
    imagejpeg($imageDst, $dst);
    // 销毁图像
    imagedestroy($imageSrc);
    imagedestroy($imageDst);
}

In the above code, we first obtain the information of the original image and create a canvas based on the original image type. Then calculate the aspect ratio and actual width and height of the thumbnail based on the target width and height of the thumbnail, create the target canvas, and use the imagecopyresampled function to copy the original image to the target canvas and resize it. Finally, save the target canvas to the specified path.

Add watermark

Adding watermarks to your website can protect the copyright of images to a certain extent. The following is the implementation method of adding watermarks to images using the GD library:

// 添加水印
function addWatermark($src, $dst, $watermark) {
    // 获取原图信息
    list($srcWidth, $srcHeight, $type) = getimagesize($src);
    // 根据原图类型创建画布
    switch ($type) {
        case IMAGETYPE_JPEG:
            $imageSrc = imagecreatefromjpeg($src);
            break;
        case IMAGETYPE_PNG:
            $imageSrc = imagecreatefrompng($src);
            break;
        case IMAGETYPE_GIF:
            $imageSrc = imagecreatefromgif($src);
            break;
        default:
            throw new Exception('不支持的图像类型');
    }
    // 获取水印图片信息
    list($watermarkWidth, $watermarkHeight) = getimagesize($watermark);
    // 创建水印画布
    $watermarkImage = imagecreatefrompng($watermark);
    // 定义水印数量和间隔
    $count = 10;
    $padding = 5;
    // 添加水印
    $posX = $padding;
    $posY = $padding;
    for ($i = 0; $i < $count; $i++) {
        imagecopy($imageSrc, $watermarkImage, $posX, $posY, 0, 0, 
            $watermarkWidth, $watermarkHeight);
        $posX += $watermarkWidth + $padding;
    }
    // 保存图片到指定路径
    imagejpeg($imageSrc, $dst);
    // 销毁图像
    imagedestroy($imageSrc);
    imagedestroy($watermarkImage);
}

In the above code, we first obtain the information of the original image and create a canvas based on the original image type. Then get the information of the watermark image and create a watermark canvas. Finally, use the imagecopy function to add the watermark in a loop. Finally, save the original image to the specified path.

The above are several examples of practical applications of the GD library in PHP. By using the GD library, we can easily process, generate and output images, making our website more colorful.

The above is the detailed content of Introducing the image processing library GD in PHP. For more information, please follow other related articles on the PHP Chinese website!

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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool