search
HomeBackend DevelopmentPHP TutorialPHP image processing function examples and PHP verification code

  1. //Prepare canvas

  2. $im = imagecreatetruecolor(500, 300);
  3. //Prepare paint

  4. $black = imagecolorallocate( $im, 0, 0, 0);
  5. $white = imagecolorallocate($im, 255, 255, 255);

  6. //The background is filled with Black

  7. imagefill($im,0,0, $black);
  8. //Draw a rectangle and fill it with white

  9. imagefilledellipse($im, 258, 151, 200, 200, $white );
  10. //Output to the browser or save it
  11. header("content-type:image/png");
  12. //Output the image
  13. imagepng($im);
  14. // Close the canvas

  15. imagedestroy($im);
  16. ?>
Copy code

php image processing function 1. Mathematical functions 2. Image processing function

Math functions: 1,max(); 2,min(); 3. mt_rand(); randomly pick a number

  1. echomt_rand(1,5);
  2. ?>
Copy code

mt_rand randomly picks a value

  1. //Randomly pick a value from an array

  2. $arr = array("a","b","c","d","e ");
  3. $rkey = mt_rand(0,count($arr)-1);

  4. echo $arr[$rkey];

  5. ?> ;
Copy code

4.ceil(); ceiling 5.floor(); 6.round(); rounding

  1. echo ceil(2.4);//3

  2. echo floor(2.4);//2
  3. echo round(2.4);//2
  4. echo round(2.6 );//3
  5. ?>

Copy code

6.pi(); //π takes pi

  1. echo(pi());
  2. echo M_PI;
  3. ?>
Copy code

image processing function usage scenarios 1.Verification code 2.Zoom 3.Crop 4. Watermark

Five steps to create an image in PHP 1. Prepare the canvas 2. Prepare paint 3. Draw images or text on the canvas 4. Output the final image or Caocun final image 5. Release canvas resources

Example:

  1. //1. Prepare canvas

  2. $im = imagecreatetruecolor(500,300);
  3. //2. Prepare paint
  4. $black = imagecolorallocate($im, 0, 0 , 0);
  5. $white = imagecolorallocate($im, 255, 255, 255);
  6. //3. Draw images or text on the canvas

  7. //If the background is not filled, the default It's black
  8. imageellipse($im,258,151,200,200,$white);
  9. //4. Output the final image or save the final image

  10. header("content-type:image/png");
  11. imagepng($im);
  12. //5. Release canvas resources
  13. imagedestroy($im);
  14. ?>
Copy the code

Draw the image: imagefill(); imagesetpixel();//draw pixels imageline();//Draw line imagerectangle();//Draw a rectangle imagepolygon();//Draw a polygon imageellipse();//Draw an ellipse imageare(); draw an arc imagechar();//Draw a character horizontally imagestring();//Draw a line of string horizontally

Example:

  1. //Draw lines

  2. //1. Prepare canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare paint
  5. $black = imagecolorallocate($ im, 0, 0, 0);
  6. $white = imagecolorallocate($im, 255, 255, 255);
  7. //3. Draw images or text on the canvas

  8. //If The background is not filled, the default is black
  9. imageline($im,0,0,500,300,$white);
  10. imageline($im,0,300,500,0,$white);
  11. imageline($im,0,150,500,150,$white);
  12. imageline( $im,250,0,250,300,$white);
  13. //4. Output the final image or save the final image

  14. header("content-type:image/png");
  15. imagepng($ im);
  16. //5. Release canvas resources
  17. imagedestroy($im);
  18. ?>
Copy code

Example:

  1. //Add interferon

  2. //1. Prepare canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare paint
  5. $black = imagecolorallocate( $im, 0, 0, 0);
  6. $white = imagecolorallocate($im, 255, 255, 255);
  7. //3. Draw images or text on the canvas

  8. // Generate random points
  9. for ($i=0; $i
  10. imagesetpixel($im,mt_rand(0,500),mt_rand(0,300),$white) ;

  11. }

  12. //Generate random lines
  13. for ($j=0; $j imageline($ im, mt_rand(0,500), mt_rand(0,300), mt_rand(0,500), mt_rand(0,300), $white);

  14. }//4. Output the final image or save the final image
  15. header("content-type:image/png ");
  16. imagepng($im);
  17. //5. Release canvas resources
  18. imagedestroy($im);
  19. ?>
Copy code

Example:

  1. //Draw a rectangle:

  2. //1. Prepare the canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare the paint
  5. $black = imagecolorallocate( $im, 0, 0, 0);
  6. $white = imagecolorallocate($im, 255, 255, 255);
  7. //3. Draw an image or text on the canvas

  8. imagerectangle( $im, 20, 20, 480, 280, $white);//
  9. imagefilledrectangle($im, 20, 20, 480, 280, $white);//Filling
  10. // 4. Output the final image or save the final image

  11. header("content-type:image/png");
  12. imagepng($im);
  13. //5. Release canvas resources
  14. imagedestroy($im);
  15. ?> < ;/p>
Copy code

Example:

  1. //imagepolygon draw polygon_draw triangle

  2. //1. Prepare canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare paint
  5. $black = imagecolorallocate($im, 0, 0, 0);
  6. $white = imagecolorallocate($im, 255, 255, 255);
  7. //3. Draw images or text on the canvas

  8. $arr = array(
  9. 250,20,
  10. 60,240,
  11. 440,240
  12. );
  13. imagepolygon($im, $arr, 3, $white);
  14. //4. Output final image or save the final image

  15. header("content-type:image/png");
  16. imagepng($im);
  17. //5. Release canvas resources
  18. imagedestroy($im);
  19. ?>
Copy the code

Example to draw a 3D pie chart

  1. //1. Prepare canvas

  2. $im = imagecreatetruecolor(500,300);
  3. //2. Prepare paint
  4. $black = imagecolorallocate($im, 0, 0 , 0);
  5. $red = imagecolorallocate($im, 255, 0, 0);
  6. $grayred = imagecolorallocate($im, 255, 100, 100);
  7. $green = imagecolorallocate($im, 0, 255, 0 );
  8. $blue = imagecolorallocate($im, 0, 0, 255);
  9. $gray = imagecolorallocate($im, 200, 200, 200);
  10. $white = imagecolorallocate($im, 255, 255, 255);
  11. //3. Draw images or text on the canvas

  12. for ($i=0; $i imagefilledarc($im, 250, 150+$ i, 200, 200, 0, 70, $gray,IMG_ARC_PIE);
  13. imagefilledarc($im, 250, 150+$i, 200, 200, 70, 190, $grayred,IMG_ARC_PIE);
  14. imagefilledarc($im, 250 p>
  15. }

  16. imagefilledarc($im, 250, 150, 200, 200, 0, 70, $white,IMG_ARC_PIE);
  17. imagefilledarc($im, 250, 150, 200, 200, 70, 190, $red,IMG_ARC_PIE);
  18. imagefilledarc($im, 250, 150, 200, 200, 190, 270, $green,IMG_ARC_PIE);
  19. imagefilledarc($im, 250, 150, 200, 200, 270, 360, $blue ,IMG_ARC_PIE);
  20. //4. Output the final image or save the final image

  21. header("content-type:image/png");
  22. imagepng($im);
  23. //5 .Release canvas resources
  24. imagedestroy($im);
  25. ?>
Copy code

Example:

  1. //Write text:

  2. //1. Prepare canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare paint
  5. $black = imagecolorallocate( $im, 0, 0, 0);
  6. $red = imagecolorallocate($im, 255, 0, 0);
  7. $grayred = imagecolorallocate($im, 255, 100, 100);
  8. $green = imagecolorallocate($im , 0, 255, 0);
  9. $blue = imagecolorallocate($im, 0, 0, 255);
  10. $gray = imagecolorallocate($im, 200, 200, 200);
  11. $white = imagecolorallocate($im, 255 , 255, 255);
  12. //3. Draw images or text on the canvas

  13. $str= "PHP is very much"; p>

  14. imagestring($im, 5, 260, 160, $str, $green);

  15. //4. Output the final image or save the final image
  16. header("content-type:image/png") ;
  17. imagepng($im);
  18. //5. Release canvas resources
  19. imagedestroy($im);
  20. ?>
Copy code

Example:

  1. //Write a single character:

  2. //1. Prepare canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare paint
  5. $black = imagecolorallocate ($im, 0, 0, 0);
  6. $red = imagecolorallocate($im, 255, 0, 0);
  7. $grayred = imagecolorallocate($im, 255, 100, 100);
  8. $green = imagecolorallocate($ im, 0, 255, 0);
  9. $blue = imagecolorallocate($im, 0, 0, 255);
  10. $gray = imagecolorallocate($im, 200, 200, 200);
  11. $white = imagecolorallocate($im, 255, 255, 255);
  12. //3. Draw images or text on the canvas

  13. $str= "P";

  14. imagechar($im, 5, 260, 160, $str, $green);

  15. //4. Output the final image or save the final image
  16. header("content-type:image/png");
  17. imagepng($im);
  18. //5. Release canvas resources
  19. imagedestroy($im);
  20. ?>
Copy code

Example,

  1. //Write on the picture

  2. //1. Prepare the canvas
  3. $im = imagecreatetruecolor(500,300);
  4. //2. Prepare the paint
  5. $black = imagecolorallocate ($im, 0, 0, 0);
  6. $red = imagecolorallocate($im, 255, 0, 0);
  7. $grayred = imagecolorallocate($im, 255, 100, 100);
  8. $green = imagecolorallocate($ im, 0, 255, 0);
  9. $blue = imagecolorallocate($im, 0, 0, 255);
  10. $gray = imagecolorallocate($im, 200, 200, 200);
  11. $white = imagecolorallocate($im, 255, 255, 255);
  12. //3. Draw images or text on the canvas

  13. $str= "junzaivip";

  14. $file = " E:/PHP/fonts/SIMYOU.TTF";
  15. // $file = "fonts/SIMYOU.TTF";
  16. imagettftext($im, 50, 0, 100, 200, $ green, $file, $str);

  17. //4. Output the final image or save the final image

  18. header("content-type:image/png");
  19. imagepng($im) ;
  20. //5. Release canvas resources
  21. imagedestroy($im);
  22. ?>
Copy code

PHP verification code design

  1. //Prepare canvas

  2. $im = imagecreatetruecolor(100,50);
  3. //Prepare paint
  4. $black = imagecolorallocate($im, 0, 0, 0 );
  5. $gray = imagecolorallocate($im, 200, 200, 200);
  6. //Fill the background

  7. imagefill($im, 0, 0, $gray); > ;
  8. //Text coordinates

  9. $x = (100-4*20)/2 + 6;
  10. $y = (50-20)/2 + 20;
  11. //Draw images or text on the canvas

  12. //Connect three arrays

  13. $strarr = array_merge(range(1, 9),range(a, z),range(A , Z));
  14. //Shuffle the array

  15. shuffle($strarr);
  16. //array_slice: Take the first few digits of the array

  17. // Join turns the array into a string, and uses the first variable as the delimiter
  18. $str = join('',array_slice($strarr, 0,4));
  19. $file = "E:/PHP/fonts/msyh.ttf";

  20. // $file = "fonts/msyh.ttf";
  21. imagettftext($im, 20, 0, $x, $ y, $black, $file, $str);

  22. //Output the final image or save the final image

  23. header("content-type:image/png");
  24. imagepng($im );
  25. //Release canvas resources
  26. imagedestroy($im);
  27. ?>
Copy code

php verification code design: This involves two pages: index.php & reg.php Description:

This verification code version only implements dynamic acquisition of verification images Compare the verification code on the front-end registration page with the verification code on the generated image The verification code is randomly composed of numbers, lowercase letters, and uppercase letters

index.php//Realize user registration

  1. reg
  2. User registration page


  3. Name: td>
    Password:
    Verification code: PHP image processing function examples and PHP verification code
    < ;/p>
Copy code

reg.php//Used to verify whether the verification code is correct

  1. session_start();

  2. // echo $_POST['username'];
  3. // echo $_POST['password'];
  4. $code = strtolower( $_POST['vcode']);
  5. // echo $code;

  6. // echo "

    "; 
  7. // print_r( $_SESSION);
  8. // echo "";
  9. $vstr = strtolower($_SESSION['vstr']);
  10. if ($code==$vstr) {

  11. //Realize page jump
  12. echo "<script>location='http://www.xingzuo51.com'</script>";
  13. }else{
  14. echo "<script>alert(' Verification code input error')</script>";
  15. //echo "Return to registration page";
  16. echo "<script>location=' index.php'</script>";
  17. }

  18. ?>
Copy code

auth.php is used to generate verification codes

  1. //Open session, there cannot be any output before opening session

  2. session_start();
  3. $width = 50; //Verification code background width
  4. $height = 26; //Verification code background high speed
  5. $fonttype = 10; //Verification code font size
  6. //Prepare canvas
  7. $im = imagecreatetruecolor($width,$height);
  8. //Prepare paint
  9. $black = imagecolorallocate($im, 0, 0, 0);
  10. $gray = imagecolorallocate($im, 200, 200, 200);
  11. //Fill the background

  12. imagefill($im, 0, 0, $gray);
  13. //Text coordinates

  14. $x = ($width-4*$fonttype)/2 +2;
  15. $y = ($height-$fonttype)/2 + $fonttype;
  16. //Draw images or text on the canvas

  17. //Connect three arrays

  18. $strarr = array_merge(range(1, 9),range(a, z),range(A, Z));
  19. //Shuffle the array

  20. shuffle($strarr); ($strarr, 0,4));
  21. //Put $str into session to facilitate use on all pages

  22. $_SESSION['vstr'] = $str; p>
  23. $file = "E:/PHP/fonts/msyh.ttf";

  24. // $file = "fonts/msyh.ttf";
  25. imagettftext($ im, $fonttype, 0, $x, $y, $black, $file, $str);

  26. //Output the final image or save the final image

  27. header("content-type: image/png");
  28. imagepng($im);
  29. //Release canvas resources
  30. imagedestroy($im);
  31. ?>
  32. Copy code
php verification code design: Page jump: 1.php jump

    $im = imagecreatefromjpeg("lyf.jpg");

  1. $x = imagesx($im);

  2. $y = imagesy($im);
  3. echo $x . $y;

  4. exit;
  5. header("content-type:image/jpeg");

  6. imagejpeg($im);
  7. ?>
  8. Copy code
Method 2 to get the size of the image:

    $imgfile = "lyf.jpg";

  1. $imgarr = getimagesize($imgfile);

  2. echo "

    "; 
  3. print_r($imgarr);
  4. echo "";
  5. exit;

  6. echo $x . $y;

  7. header("content-type:image/jpeg ");

  8. imagejpeg($im);
  9. ?>
  10. Copy code

Image zoom function:

  1. $imgfile = "lyf.jpg";

  2. //In order to get the width and height of the large image

  3. $imgarr = getimagesize( $imgfile);
  4. $maxw = $imgarr[0];

  5. $maxh = $imgarr[1];
  6. $maxt = $imgarr[2];
  7. $maxm = $imgarr[ 'mime'];
  8. //In order to turn large images into resources

  9. $im = imagecreatefromjpeg("lyf.jpg");

    > ;
  10. //Small image resources

  11. $minw = 100;
  12. $minh = 400;
  13. //Equal scaling
  14. if (($minw/$maxw)> ;($minh/$maxh)) {
  15. $rate = $minh/$maxh ;
  16. }else{
  17. $rate = $minw / $maxw ;
  18. }
  19. $minw = floor ($maxw * $rate);

  20. $minh = floor($maxh * $rate);
  21. $minim = imagecreatetruecolor($minw, $minh);
  22. //Zoom the large image Into a small image

  23. imagecopyresampled($minim, $im, 0, 0, 0, 0, $minw, $minh, $maxw, $maxh);
  24. //Small image output

  25. header ("content-type:{$maxm}");
  26. //Determine the type

  27. switch ($maxt) {
  28. case 1:
  29. $imageout = "imagegif";
  30. break;
  31. case 2:
  32. $imageout = "imagejpeg";
  33. break;
  34. case 3:
  35. $imageout = "imagepng";
  36. break;
  37. }

  38. $imageout($minim);

  39. $minfilename = "s_".$imgfile;
  40. $imageout($minim,$minfilename);
  41. // imagejpeg($im);
  42. / /Release resources
  43. imagedestroy($maxim);
  44. imagedestroy($minim);
  45. ?>
Copy code

Image cropping function: imagecopyresampled();

Image watermark function: imagecopy();

3, Crop

4, watermark

  1. $maxim = imagecreatefromjpeg("lyf.jpg");

  2. $minim = imagecreatefromjpeg("lyf.jpg");
  3. $maxh = imagesy($maxim);

  4. $minw = imagesx($minim);

  5. $minh = imagesy($minim); < ;/p>
  6. imagecopy($maxim, $minim, $maxw-$minw, $maxh-$minh, 0, 0, $minw, $minh);

  7. header("content-type:image/jpeg");

  8. imagejpeg($mamim);

  9. ?>
Copy code


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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools