search
HomeBackend DevelopmentPHP TutorialPHP graphics image manipulation

Introduction to GD library

GD refers to Graphic Device. PHP's GD library is an extension library for processing graphics. Through a series of APIs provided by the GD library, images can be processed or new pictures can be directly generated.

In addition to text processing, PHP can also process JPG, PNG, GIF, SWF and other images through the GD library. The GD library is commonly used in image watermarking, verification code generation, etc.

PHP has integrated the GD library by default, you just need to enable it during installation.

<span>header("content-type: image/png"); $img=imagecreatetruecolor(100, 100); $red=imagecolorallocate($img, 0xFF, 0x00, 0x00); imagefill($img, 0, 0, $red); imagepng($img); imagedestroy($img);<span><span></span></span></span></preubuntu></divmicrosoft></p> <divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p><span>Draw lines</span></p> <p><divmicrosoft yahei sans gb neue font-size:14px><p><span>To operate graphics, first create a new canvas, and create a true-color blank picture through the imagecreatetruecolor function: </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$img = imagecreatetruecolor(100, 100);</span><p><span>In the GD library for The color used by the brush needs to be allocated through the imagecolorallocate function. The color of the brush is determined by setting the RGB color value via parameters: </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$red = imagecolorallocate($img, 0xFF, 0x00, 0x00);</span><p><span> Then we draw the line by calling the line segment function imageline, and specify the starting point and end point. Finally get lines. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>imageline($img, 0, 0, 100, 100, $red);</span><p><span>After the lines are drawn, the image is output through header and imagepng. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>header("content-type: image/png"); imagepng($img);</span><p><span>Finally, you can call imagedestroy to release the memory occupied by the image. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>imagedestroy($img);</span><p><span>Through the above steps, you can find that drawing graphics with PHP is very simple, but many times we not only need to output pictures, we may also need to get an image file. We can specify the file name through the imagepng function to save the drawn image. into the file. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>imagepng($img, 'img.png');</span></preubuntu></preubuntu></preubuntu></preubuntu></preubuntu></preubuntu></divmicrosoft></p> <divmicrosoft yahei sans gb neue font-size:14px line-height:21px><p>Draw text in images</p> <p><divmicrosoft yahei sans gb neue font-size:14px><p><span>The GD library can perform a variety of basic graphics operations. Commonly used ones include drawing lines, background filling, drawing rectangles, drawing text, etc. </span></p> <p><span>Similar to drawing lines, you first need to create a new picture and initialize the color. </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$img = imagecreatetruecolor(100, 100); $red = imagecolorallocate($img, 0xFF, 0x00, 0x00);</span><p><span>Then use the imagestring function to draw text. This function has many parameters: imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col ), which can be passed $font sets the font size, x and y set the text display position, $s is the text to be drawn, and $col is the color of the text. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>imagestring($img, 5, 0, 0, "Hello world", $red); header("content-type: image/png"); imagepng($img); imagedestroy</span><span>($img); </span></preubuntu></preubuntu></divmicrosoft></p> <p><span>Output image file</span></p> <p><divmicrosoft yahei sans gb neue font-size:14px><p><span>We have learned earlier that imagepng can directly output images to the browser, but many times, we want to save the processed image to a file so that Can be used multiple times. Save the image to a file by specifying the path parameter. </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$filename = 'img.png'; imagepng($img, $filename);</span><p><span>Use imagepng to save the image into png format. If you want to save it into other formats, you need to use different functions. Use imagejpeg to save the image into jpeg format, and imagegif to save the image into gif format. It should be noted that imagejpeg The image is compressed, so a quality parameter can also be set. </span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>$filename = 'img.jpg'; ?imagejpeg($img, $filename, 80);</span></preubuntu></preubuntu></divmicrosoft></p> <p>Generate image verification code</p> <p><divmicrosoft yahei sans gb neue font-size:14px><p><span>A simple verification code actually outputs a few characters in the picture, which can be achieved through the imagestring function we mentioned in the previous chapter. </span></p> <p><span>But in terms of processing, in order to make the verification code more secure and prevent other programs from automatically recognizing it, it is often necessary to perform some interference processing on the verification code. Usually, some noise points are drawn, interference line segments are drawn, and the output characters are tilted , twist and other operations. </span></p> <p><span>You can use imagesetpixel to draw points to achieve noise interference, but drawing only one point has little effect, so loops are often used here to draw randomly. </span></p> <preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>for($i=0;$i<span></span></span></preubuntu></divmicrosoft></p> <br><p><br></p> <pre name="code"><?php $img = imagecreatetruecolor(100, 40); $black = imagecolorallocate($img, 0x00, 0x00, 0x00); $green = imagecolorallocate($img, 0x00, 0xFF, 0x00); $white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF); imagefill($img,0,0,$white); //生成随机的验证码 $code = &#39;&#39;; for($i = 0; $i < 4; $i++) { $code .= rand(0, 9); } imagestring($img, 5, 10, 10, $code, $black); //加入噪点干扰 for($i=0;$i<50;$i++) { imagesetpixel($img, rand(0, 100) , rand(0, 100) , $black); imagesetpixel($img, rand(0, 100) , rand(0, 100) , $green); } //输出验证码 header("content-type: image/png"); imagepng($img); imagedestroy($img);

Add watermark to pictures

There are generally two ways to add watermarks to pictures, one is to add a string to the picture, the other is to add a watermark to the picture Add a logo or other picture.

Because what is being processed here is an existing image, you can create a canvas directly from an existing image, and create an image directly from an image file through imagecreatefromjpeg.

<span>$im = imagecreatefromjpeg($filename);</span></preubuntu></divmicrosoft></p>

创建图像对象以后,我们就可以通过前面的GD函数,绘制字符串到图像上。如果要加的水印是一个logo图片,那么就需要再建立一个图像对象,然后通过GD函数imagecopy将logo的图像复制到源图像中。

<span>$logo = imagecreatefrompng($filename); imagecopy($im, $logo, 15, 15, 0, 0, $width, $height);</span><p><span>当将logo图片复制到原图片上以后,将加水印后的图片输出保存就完成了加水印处理。</span></p><preubuntu mono line-height:1.6em font-size:13px word-break:break-word><span>imagejpeg(</span><span>$im, $filename); </span><br><p></p><pre name="code"><?php //这里仅仅是为了案例需要准备一些素材图片 $url = &#39;http://www.iyi8.com/uploadfile/2014/0521/20140521105216901.jpg&#39;; $content = file_get_contents($url); $filename = &#39;tmp.jpg&#39;; file_put_contents($filename, $content); $url = &#39;http://wiki.ubuntu.org.cn/images/3/3b/Qref_Edubuntu_Logo.png&#39;; file_put_contents(&#39;logo.png&#39;, file_get_contents($url)); //开始添加水印操作 $im = imagecreatefromjpeg($filename); $logo = imagecreatefrompng(&#39;logo.png&#39;); $size = getimagesize(&#39;logo.png&#39;); imagecopy($im, $logo, 15, 15, 0, 0, $size[0], $size[1]); header("content-type: image/jpeg"); imagejpeg($im);

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了PHP图形图像操作,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool