Core PHP Programming --GD image processing

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/yangmolulu/article/details/91478570

Image processing techniques GD

table of Contents

Image processing techniques GD

Introduction and presentation of the GD library

Create a canvas resources

Operating canvas resources

Output canvas resources

Destruction canvas resources

Get Picture information

Achieve verification code

Thumbnail realization

The watermark


Introduction and presentation of the GD library

API: Application interface to the outside, ready mechanism to deal with a certain function, users only need to follow the specific data requirements, call the specified function or method (class) can achieve a certain function.

1) GD library concept: Graphics Device, the image extension processing (API externally provided), can allow use of the corresponding function in the PHP script to achieve some image creation function

2) introducing the library GD: GD API library is externally provided, it has been integrated into PHP extension library (no download), but requires a corresponding opening in the PHP extension profile. GD extension (GD2)

Note: Remember to restart Apache

 

Create a canvas resources

1) imagecreate (int $ x_size, int $ y_size): Create a blank canvas (background color is white)

2) imagecreatetruecolor (int $ width, int $ height): create a true-color canvas (background color is black, need to be filled)

 

3) imagecreatefromjpeg (string $ filename): open the picture in jpeg format of a resource

4) imagecreatefromgif (string $ filename): Open a resource GIF format (PHP can not be achieved dynamic)

5) imagecreatefrompng (string $ filename): Open the png format images resources

If you create a picture from a known resource file, be sure to match the Open, otherwise it will go wrong.

 

Operating canvas resources

Note: All operations are required to specify resource canvas canvas resources, and are the first argument

 

1) Color distribution: imagecolorallocate (resource $ image, int $ red, int $ green, int $ blue): RGB triads assigned a set of resources according to a color to the canvas, returns a handle to the color (a set of integers).

In the true color picture resource, the color of all allocated resources are not automatically color to the picture, the picture is used to follow-up operation resources when the designated colored; but if you are currently using resources imagecreate picture created, then the first distribution colors, it will automatically be colored picture background color.

Note: Any increase to the picture content, the basic need to assign a color (function before each operation picture, you need to call a function to assign colors to get a color).

2) filled region: imagefill (resource $ image, int $ x, int $ y, int $ color): Specifies the location specified color begins to fill

Imagefill fill logic: automatic matching starts from the specified point adjacent to the point, if the same color, rendering automatically extended to full FIG.

3) draw a straight line: imageline (resource $ image, int $ x1, int $ y1, int $ x2, int $ y2, int $ color): make a straight line

4) drawing a rectangle: imagerectangle (resource $ image, int $ x1, int $ y1, int $ x2, int $ y2, int $ color): Make a rectangle

5) Draw an arc: imagearc (resource $ image, int $ cx, int $ cy, int $ w, int $ h, int $ s, int $ e, int $ color): imagearc () to cx, cy (Image the upper left corner is 0, 0) as the center of a draw an arc in the image represented by the. w and h specifies the width and height of the ellipse, to specify the start and end points s and e angle parameters. Located at the three o'clock position of 0 °, in a clockwise direction drawing.

6) on the canvas to write:

imagestring (resource $ image, int $ font, int $ x, int $ y, string $ s, int $ col): it is used to write characters (English) ASCII corresponding, imagestring () with the color col string s to Videos x represents an image image, y coordinates (which is a string left corner, the upper left corner of the entire image is 0,0). If the font is 3, 4 or 5, use the built-in font.

 imagettftext (resource $ image, float $ size, float $ angle, int $ x, int $ y, int $ color, string $ fontfile, string $ text): Mathematics for any text (Chinese). Need to specify the font path (ttf file: Default is Windows / fonts /)

 

Output canvas resources

1) the output image files; save to a local folder with a picture file form

2) output as a Web page picture: Take a photo tour to HTML (user): server needs to tell the server to the current content is a picture (to modify the response header)

Image + Image Format: The return value bool

imagejpeg (resource $ image [, string $ filename [, int $ quality]]): save as jpg format pictures, quality is optional, ranging from 0 (worst quality, smaller file) to 100 (best quality, file maximum). The default is the default IJG quality value (about 75).

imagepng (resource $ image [, string $ filename]): Images saved as png format

imagegif (resource $ image [, string $ filename]): Save GIF format images

 

If the picture only provides a picture of the resources, do not specify a location to save the file, the system thought to be output to the browser; if the storage location is specified, the system considers to be saved to the local (second parameter).

 

 

细节1:如果图片输出或者保存出错,浏览器看到的永远是告诉你图片错了,但是绝对不会告知错误原因在哪,需要关闭header图片输出,再看问题。

 

 

细节2:如果图片输出之后没有成功,但是关闭header之后也看不到错误:最大的可能是图片输出之前输出了别的额外的内容(喜欢输出pre),应该查看网页源码,看看图片输出之前是否有任何输出:尤其是空格空行

销毁画布资源

从内存中将画布资源清理掉,释放内存。

imagedestory(resource $image)

 

获取图片信息

1)获取画布尺寸:imagesx(resource $image),imagesy(resource $image)

2)获取图片尺寸:getimagesize(string $filename [, array &$imageinfo ])

 

 

 

 

 

验证码的实现

验证码(CAPTCHA),全自动区分计算机和人类的图灵测试的缩写。由计算机生成并评判,但是必须只有人类才能解答。

图片验证码:计算机将拿到的验证码存放到图片中,然后用户看到然后识别,然后提交给服务器,服务器再根据用户提交的和服务器之前生成的进行比较。

1)实现验证码图片展示

a.生成图片资源:背景色设定

b.生成文字

c.输出图片给浏览器

d.关闭资源

 

2)实现验证码文字的随机变换:有一串文字可以随机选择

a.制作目标字符串集:从哪里选内容

b.如何随机从字符串中取出对应的汉字:含在在utf-8字符集中一个字占用3个字节,英文字母只占一个字节。

c.随机取出字符

d.将取到的字符放在图片指定位置

 

3)实现验证码文字的颜色的随机变化

 

4)实现验证码背景或干扰噪点:增加一些额外不影响用户看,但是会产生模糊效果的内容,(点或者线):imagestring/imageline/imagesetpixel

imagesetpixel — 画一个单一像素

改变文字大小和位置以及其他可变信息

 

 

5)实现点击刷新验证码功能:实现验证码在浏览器显示的功能

a.创建一个表单文件,里面有一个img标签能够显示图片

b.实现点击更换验证码。让HTML重新请求PHP脚本,产生一张新的图片。因此需要增加一个点击事件:img的src是否重新发起请求,取决于浏览器;浏览器是否重新发起请求,取决于src是否改变。如何让其点击一次变换一次。

 

 

缩略图的实现

1)制作图片缩略图的原理:

缩略图:将原图得到一个较小的图(尺寸上)

缩略图原理:将原图打开,然后放到另一个较小的图片资源中,最后进行保存即可。

2)实现固定宽高的缩略图

a.得到一张原图资源

b.得到一个缩略图资源

c.实现图片采样复制:GD提供了函数:imagecopyresampled(resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h)

d.保存缩略图

e.销毁所有资源:原图和缩略图

 

3)实现等比例缩放的固定宽或高的缩略图

优点:图片不会变形

缺点:缩略图有些部分需要进行额外填充(白色填充:补白)

1、计算缩略图宽高比和原图宽高比

2、如果缩略图宽高比大于原图宽高比,将缩略图中用原图的高尽可能填满:缩略图的高是完整的,宽度不够(补白);如果缩略图的宽高比小于原图宽高比,将缩略图中用原图的宽尽可能填满:缩略图宽是完整的,高度不够(补白)

3、将图片放到缩略图中间

 

 

 

水印图

水印图:watermark,在某个图片上增加一个透明的印记(马赛克)

水印图用途:版权操作

1)制作图片水印图的原理

水印图制作原理:将一个带有明显标志的图片放到另外一张需要处理的图片之上。

2)实现固定位置的水印图:左上角

a.获取原图资源(放上水印图)

b.获取水印图资源

c.合并图片(把图片合到目标图上)

imagecopymerge(resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct)

将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度,其值范围从 0 到 100。当 pct = 0 时,实际上什么也没做,当为 100 时对于调色板图像本函数和 imagecopy() 完全一样,它对真彩色图像实现了 alpha 透明。

d.保存输出

e.清除资源

 

3)实现可选9个位置的水印图:封装制作水印图的函数

a.创建一个制作水印图的函数结构:制作水印图需要提供哪些条件?原图资源,水印图资源,位置选择?9个 透明度,保存位置路径

b.结果是希望产生水印图,但是可能产生成功,返回文件保存名字。但是如果产生失败,返回false,但是还需要告知外界原因:通过引用传参解决

c.水印图前提:原图和对应的水印图都存在

d.判定保存路径是否存在

e.打开原图和水印图资源

1)想办法确定用什么函数来打开图片资源,通过图片的MIME类型:获取图片信息

2)通过MIME类型得到要打开图片的函数:先设定一个数组进行匹配,匹配成功,自动构造创建函数(保存函数)失败则提示错误

3)匹配数据

4)组合函数名字:打开原图资源函数,打开水印图函数,保存水印图函数

f.合并图片资源:产生水印,位置需要计算

1)计算水印提在原图中的位置

2)合并图片资源

g.保存水印图片和销毁资源

 

实现代码:

<?php



       //制作水印图制作函数



       /*

        *@param1 string $src_image,原图路径

        *@param2 string $wat_image,水印图路径

        *@param3 string $path,水印图存储路径

        *@param4 string $error,记录错误信息的变量

        *@param5 int $position = 1,水印图加载位置:1代表左上角以此类推9代表右下角

        *@param6 int $pct = 20,透明度,默认20

       */



       function watermark($src_image,$wat_image,$path,&$error,$position = 1,$pct = 20){

              //验证原图和水印图都存在

              if(!is_file($src_image)){

                     $error = '原图不存在!';

                     return false;

              }

             

              if(!is_file($wat_image)){

                     $error = '水印图不存在!';

                     return false;

              }



              //判定路径保存是否存在

              if(!is_dir($path)){

                     $error = '保存位置不正确!';

                     return false;

              }

             

              //获取图片信息

              $src_info = getimagesize($src_image);

              $wat_info = getimagesize($wat_image);



              //定义一组数据:用来产生对应图片

              $allow=array(

                     'image/jpeg' => 'jpeg',

                     'image/jpg' => 'jpeg',

                     'image/gif' => 'gif',

                     'image/png' => 'png',

                     'image/pjpeg' => 'pjpeg',

                     'image/jpeg' => 'jpeg'    

              );

             

              //匹配数据

              if(!array_key_exists($src_info['mime'],$allow)){

                     $error = '当前文件资源不允许制作水印图';

                     return false;

              }



              if(!array_key_exists($wat_info['mime'],$allow)){

                     $error = '当前水印图不允许做资源使用!';

                     return false;

              }



              //组合函数

              $src_open = 'imagecreatefrom'.$allow[$src_info['mime']];

              $wat_open = 'imagecreatefrom'.$allow[$wat_info['mime']];

              $src_save = 'image'.$allow[$src_info['mime']];



              //打开资源

              $src = $src_open($src_image);

              $wat = $wat_open($wat_image);



              //计算水印图在原图中的位置

              $start_x = $start_y = 0;

              switch($position){

                     case 1:           //左上角

                            break;    

                     case 2:           //上中间

                            $start_x = ceil(($src_info[0] - $wat_info[0]) / 2);

                            break;

                     case 3:           //右上

                            $start_x = $src_info[0] - $wat_info[0];

                            break;

                     case 4:           //中左

                            $start_y = ceil(($src_info[1] - $wat_info[1]) / 2);

                            break;

                     case 5:           //正中

                            $start_x = ceil(($src_info[0] - $wat_info[0]) / 2);

                            $start_y = ceil(($src_info[1] - $wat_info[1]) / 2);

                            break;

                     case 6:           //中右

                            $start_x = $src_info[0] - $wat_info[0];

                            $start_y = ceil(($src_info[1] - $wat_info[1]) / 2);

                            break;

                     case 7:           //下左

                            $start_y = $src_info[1] - $wat_info[1];

                            break;

                     case 8:           //下中

                            $start_x = ceil(($src_info[0] - $wat_info[0]) / 2);

                            $start_y = $src_info[1] - $wat_info[1];

                            break;

                     case 9:           //下右

                            $start_x = $src_info[0] - $wat_info[0];

                            $start_y = $src_info[1] - $wat_info[1];

                            break;

                     default:

                            $error = '位置信息错误!(请选择数字1-9)';

                            return false;

              }





              //合并图片资源

              if(imagecopymerge($src,$wat,$start_x,$start_y,0,0,$wat_info[0],$wat_info[1],$pct)){

                     //成功  保存图片

                     //header('Content-type:'.$src_info['mime']);

                     $filename = 'watermark_'.trim(strrchr($src_image,'/'),'/');

                     //echo $filename;exit;

                     $src_save($src,$path.'/'.$filename);

                     //销毁资源

                     imagedestroy($src);

                     imagedestroy($wat);

                     return $filename;

              }else{

                     //失败

                     $error = '水印图制作(合并)失败!';

                     return false;

              }

       }



       //调用函数

       $res = watermark('../uploads/315177.jpg','water.jpg',__DIR__,$error,10);

       if($res){

              echo $res;

       }

       else{

              echo $error;

       }

 

Guess you like

Origin blog.csdn.net/yangmolulu/article/details/91478570