003_PHP core 03

Today 1.1 goals

  1. Understanding of PHP extensions loaded;
  2. GD library to know what to do;
  3. Master GD library for verification code function;
  4. Master GD library for thumbnails;
  5. Master the GD library implements the watermark function;
  6. Grasp the principle of verification verification code;

1.2 open GD extension

GD library is used to process the image. Use GD library, first open the gd extension in php.ini

extension=php_gd2.dll

After the open you can use the function at the beginning of the image.

1.3 Create a simple picture

step

1. Create a canvas

2, the fill color to the canvas (canvas assigned to the first color to the background color is automatically populated)

3, display pictures

<?php
$img=imagecreate(200,100);	//创建图片
//var_dump($img);		//resource(2) of type (gd) 
imagecolorallocate($img,255,0,0);	//给图片分配第一个颜色,默认是背景色
//操作一:显示图片
/*
//告知浏览器用jpg格式显示
header('content-type:image/jpeg');
//显示图片
imagejpeg($img);	//用jpg格式显示图片
*/

//操作二:保存图片(不需要设置header头)
imagejpeg($img,'./tu.jpg');

Learn a trick

imagepng():将图片输出为png格式
imagegif():将图片输出为gif格式

summary:

1, the first color is assigned a background color

2. To display the canvas in a browser, you need to set header () head

3, save canvas, need not be provided header () head

1.4 Fill Color

The first color distribution picture to fill automatically to the background color, the background color to be replaced if the need to manually fill color.

<?php
$img=imagecreate(200,100);	//创建图片资源
$color=imagecolorallocate($img,200,200,200);
//更改背景色
switch(rand(1,100)%3) {
	case 0:
		$color=imagecolorallocate($img,255,0,0);	//颜色的索引编号
		break;
	case 1:
		$color=imagecolorallocate($img,0,255,0);
		break;
	default:
		$color=imagecolorallocate($img,0,0,255);
}
//填充颜色
imagefill($img,0,0,$color);	
//显示图片
header('content-type:image/png');
imagepng($img);

1.5 PIN

1.5.1 codes of action

Prevent brute force

1.5.2 Principle

Create a picture, write a bunch of random string in the picture

Implementation steps:

Step 1: Generate a random string

Step 2: Create a canvas

The third step: the string to the canvas

imagestring(图片资源,内置字体,起始点x,起始点y,字符串,颜色编号)

Difficulty: string center

1.5.3 code implementation

<?php
//第一步:创建随机字符串
//1.1  创建字符数组
$all_array=array_merge(range('a','z'),range('A','Z'),range(0,9));	//所有字符数组
$div_array=['1','l','0','o','O','I'];	//去除容易混淆的字符
$array=array_diff($all_array,$div_array);	//剩余的字符数组
unset($all_array,$div_array);		//销毁不需要使用的数组
//1.2	随机获取4个字符
$index=array_rand($array,4);	//随机取4个字符,返回字符下标,按先后顺序排列
shuffle($index);	//打乱字符
//1.3	通过下标拼接字符串
$code='';
foreach($index as $i){
	$code.=$array[$i];
}
//第二步:创建画布
$img=imagecreate(150,30);
imagecolorallocate($img,255,0,0);			//分配背景色
$color=imagecolorallocate($img,255,255,255);	//分配前景色
//第三步:将字符串写到画布上
$font=5;		//内置5号字体
$x=(imagesx($img)-imagefontwidth($font)*strlen($code))/2;
$y=(imagesy($img)-imagefontheight($font))/2;
imagestring($img,$font,$x,$y,$code,$color);
//显示验证码
header('content-type:image/gif');
imagegif($img);

summary

  1. range (): generating an array of the specified range
  2. array_merge (): Array Merge
  3. array_diff (): Set the array for calculating a difference
  4. array_rand (): Gets an array of random elements
  5. shuffle (): Array upset
  6. Remove the character confusing
  7. To disrupt the array
  8. Number - (width of the picture string width) / 2 = width of the string * character width of characters starting point x =
  9. The starting point y = (height of the image - character height) / 2

operation result

1.6 Open the image to create a verification code

step:

1, generates a random string

2, open the picture

3, the string is written on the picture

Code

<?php
//第一步:生成随机字符串
$codeSet='2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
$code='';
$max=strlen($codeSet);
for($i=1;$i<=4;$i++){
	$index=rand(0,$max-1);
	$code.=$codeSet[$index];
}
//第二步:打开图片
$path='./captcha/captcha_bg'.rand(1,5).'.jpg';
$img=imagecreatefromjpeg($path);
//第三步:将字符串写到图片上
$font=5;		//内置5号字体
$x=(imagesx($img)-imagefontwidth($font)*strlen($code))/2;
$y=(imagesy($img)-imagefontheight($font))/2;
//随机前景色
$color=imagecolorallocate($img,255,255,255);	//设置背景色
if(rand(1,100)%2)
	$color=imagecolorallocate($img,255,0,0);	//设置背景色	

imagestring($img,$font,$x,$y,$code,$color);
//显示验证码
header('content-type:image/gif');
imagegif($img);

operation result

Learn a trick: captcha

1.7 Chinese Code

1.7.1 steps and thinking

Think

1, Chinese code requires the introduction of font files, built-in font does not support Chinese

2, the use of imagettftext(图片资源,字号大小,角度,起始x坐标,起始y坐标,颜色,字体文件地址,字符串)written Chinese

3, fonts stored in C:\Windows\Fontsthe directory

4, with the imagettfbbox()measured width and height of the Chinese character string, the function returns the value 8, the coordinates of the four corners of

step

1, generates a random string

2. Create a canvas

3, the string is written on the canvas

1.7.2 code implementation

The black body copy to ttf directory sites

Code

<?php
//第一步:生成随机字符串
$codeSet='们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来';
$max=mb_strlen($codeSet)-1;	//中文字符的最大索引号
$code='';
for($i=0; $i<4; $i++) {
	$start=rand(0,$max);
	$code.=mb_substr($codeSet,$start,1);
}
//第二步:创建画布
$img=imagecreate(150,40);
imagecolorallocate($img,255,0,0);
//第三步:将字符串写到画布上
//3.1  指定字符串的参数
$color=imagecolorallocate($img,255,255,255);
$size=15;	//字号
$angle=0;	//角度
$fontfile='./ttf/simhei.ttf';	//字体路径
//3.2 测定字符串的范围
$info=imagettfbbox($size,$angle,$fontfile,$code);
$code_w=$info[4]-$info[6];	//字符串的宽度
$code_h=$info[1]-$info[7];	//字符串的高度

$x=(imagesx($img)-$code_w)/2;	//起始点的$x
$y=(imagesy($img)+$code_h)/2;	//起始点的$y
//3.3  将中文字符串写到画布上
imagettftext($img,$size,$angle,$x,$y,$color,$fontfile,$code);	//将文字写到画布上
//显示验证码
header('content-type:image/jpeg');
imagejpeg($img);

summary

1, Chinese processing necessary for processing multi-byte

2, multi-byte handler need to open the corresponding extension

extension=php_mbstring.dll

3, using the imagettfbboxmeasurement range of the Chinese character string

4, imagettftextthe Chinese written on the canvas

1.8 Watermark

1.8.1 Text Watermark

  1. Add text or picture in the picture, purpose: propaganda against Pirates
  2. There watermark image watermark and text watermark.
  3. The principle and Chinese text watermark verification code is the same

step

1. Open the picture

2, the text is written on the picture

3, the output picture (Save Picture)

achieve

<?php
//第一步:打开图片
$img=imagecreatefromjpeg('./face.jpg');
//第二步:将文字写到图片上
$color=imagecolorallocate($img,255,0,0);
$size=35;	//字号
$angle=0;	//角度
$fontfile='./ttf/simhei.ttf';	//字体路径
$code='传智播客黑马程序员';

$info=imagettfbbox($size,$angle,$fontfile,$code);
$code_w=$info[4]-$info[6];	//字符串的宽度
$code_h=$info[1]-$info[7];	//字符串的高度

$x=imagesx($img)-$code_w;	//起始点的$x
$y=imagesy($img)-$code_h;	//起始点的$y
//将中文字符串写到画布上
imagettftext($img,$size,$angle,$x,$y,$color,$fontfile,$code);	//将文字写到画布上
//第三步:保存图片
imagejpeg($img,'./face.jpg');

Achieve results

1.8.2 picture watermark

Principle: The watermark image copy is copied to the target picture.

step:

1, FIG Open Source

2, FIG target opening

3, FIG copy source are copied to the target FIG.

achieve

<?php
//第一步:打开源图
$src_img=imagecreatefromjpeg('./water.jpg');
//第二步:打开目标图
$dst_img=imagecreatefromjpeg('./face.jpg');
//第三步:将源图复制到目标图上
$dst_x=imagesx($dst_img)-imagesx($src_img);   //开始粘贴的x
$dst_y=imagesy($dst_img)-imagesy($src_img);	  //开始粘贴的y
$src_w=imagesx($src_img);
$src_h=imagesy($src_img);
imagecopy($dst_img,$src_img,$dst_x,$dst_y,0,0,$src_w,$src_h);
//显示水印图
header('content-type:image/jpeg');
imagejpeg($dst_img);

operation result

1.9 Thumbnails

After upload pictures, the pictures become unified thumbnail size.

Principle: The source image are copied to the target map, and zoom.

step

1, create a destination map

2, FIG Open Source

3, FIG copy source, the copy to the target FIG.

Code

<?php
//第一步:创建目标图
$dst_img=imagecreatetruecolor(200,200);
//第二步:打开源图
$src_img=imagecreatefromjpeg('./face.jpg');
//第三步:复制源图拷贝到目标图上,并缩放大小
$src_w=imagesx($src_img);
$src_h=imagesy($src_img);
imagecopyresampled($dst_img,$src_img,0,0,0,0,200,200,$src_w,$src_h);
//第四步:保存缩略图
//header('content-type:image/jpeg');
imagejpeg($dst_img,'./face1.jpg');

Note: imagecreate()and imagecreatetruecolor()distinction

imagecreate():创建支持256种颜色的画布
imagecreatetruecolor():创建真彩色画布,支持256*256*256种颜色

1.10 error correction code

Verification code error does not report specific error message

The first one: Notes header

After commented header, an error message came out

The second measure: If there is no error, we look carefully whether the code string output before the picture, in front of the picture is not allowed to have any string output

The third measure: View source code, if there is a blank character before the picture codes

The fourth one: If the above three measures invalid, the header () before adding ob_clean ();

1.11 achieved in the project code

1.11.1 Class package codes

1, the verification code in the package library Lib

2. Create Captcha.class.php page in the Lib directory

<?php
namespace Lib;
class Captcha{
    private $width;
    private $height;
    public function __construct($width=80,$height=32) {
        $this->width=$width;
        $this->height=$height;
    }
    //生成随机字符串
    private function generalCode(){
        $all_array=array_merge(range('a','z'),range('A','Z'),range(0,9));	//所有字符数组
        $div_array=['1','l','0','o','O','I'];	//去除容易混淆的字符
        $array=array_diff($all_array,$div_array);	//剩余的字符数组
        unset($all_array,$div_array);		//销毁不需要使用的数组
        $index=array_rand($array,4);	//随机取4个字符,返回字符下标,按先后顺序排列
        shuffle($index);	//打乱字符
        $code='';
        foreach($index as $i)
            $code.=$array[$i];
        $_SESSION['code']=$code;        //保存到会话中
        return $code;
    }
    //创建验证码
    public function entry(){
        $code=$this->generalCode();
        $img=imagecreate($this->width, $this->height);
        imagecolorallocate($img,255,0,0);			//分配背景色
        $color=imagecolorallocate($img,255,255,255);	//分配前景色
        $font=5;		//内置5号字体
        $x=(imagesx($img)-imagefontwidth($font)*strlen($code))/2;
        $y=(imagesy($img)-imagefontheight($font))/2;
        imagestring($img,$font,$x,$y,$code,$color);
        //显示验证码
        header('content-type:image/gif');
        imagegif($img);
    }
    //验证码比较
    public function check($code){
        return strtoupper($code)== strtoupper($_SESSION['code']);
    }
}

Use Code 1.11.2

1, the controller calls the class codes (the LoginController)

public function verifyAction(){
    $captcha=new \Lib\Captcha();
    $captcha->entry();
}

2, the page displayed in the view codes

<img src="index.php?p=Admin&c=Login&a=verify" width="80" height="32" class="passcode" onclick='this.src="index.php?p=Admin&c=Login&a=verify&"+Math.random()' />

The reason is to add a random number to make the URL address becomes the only prevent the browser cache.

3, the check-codes

public function loginAction(){
    //第二步:执行登陆逻辑
    if(!empty($_POST)){
        //校验验证码
        $captcha=new \Lib\Captcha();
        if(!$captcha->check($_POST['passcode']))
            $this->error ('index.php?p=Admin&c=Login&a=login', '验证码错误');
        ...

operation result

1.12 function used

imagecreate():创建画布
imagecreatetruecolor():创建支持真彩色的画布
imagecolorallocate():给画布分配颜色
imagejpeg():将图片以jpeg格式输出
imagegif():将图片以gif格式输出
imagepng():将图片以png格式输出
imagefill():填充颜色
imagesx():获取图片宽度
imagesy():获取图片高度
imagefontwidth():获取内置字体宽度
imagefontheight():获取内置字体高度
imagestring():将字符串写到图片上
imagecreatefromjpeg():打开jpg创建图片资源
imagecreatefrompng():打开png创建图片资源
imagecreatefromgif():打开gif创建图片资源
imagettfbbox():测定中文字体的范围
imagettftext():将中文字体写到图片上
imagecopy():图片拷贝
imagedestroy():销毁图片资源
imagecopyresampled():拷贝图片并缩放大小

Guess you like

Origin www.cnblogs.com/xeclass/p/12657520.html