PHP基础 —— 图形处理

图像处理

GD和图像处理,不仅可以创建文件,而且可以处理已有图像

创建图像基本步骤

  1. 创建图像
  • 所有的操作都需要在此图像上完成
  1. 绘制图像
  • 创建完成后,进行设置图像的颜色,填充画布,画线,画点等
  1. 输出图像
  • 绘制完成,与要将图像以某种格式保存到服务器文件中,或者直接展示到浏览器上,在输出到浏览器之前,
  • 一定要使用使用header()函数发送Content type通知浏览器,这是图片不是文件
  1. 释放资源
创建图像
  1. 创建新图像

imagecreatetruecolor(); —— GD图像

imagecreatetruecolor (  $width ,  $height ) ;

$width —— 图像宽度

$height —— 图像高度

返回值:成功后返回图像资源,失败后返回false

  1. 打开服务器或者网络文件中存在的GIF,JPEG,PNG,WBNP

由文件或 URL 创建一个新图象

imagecreatefrombmp ( $filename ) ; —— 打开一个BMP图片文件,创建图像
imagecreatefromgd2 ( $filename ) ; —— 打开一个GD2文件
imagecreatefromgd ( $filename ) ; —— 打开一个GD文件
imagecreatefromgif ( $filename ) ; —— 打开一个GIF图像文件
imagecreatefromjpeg( $filename ) ; —— 打开一个JPEG图像文件
imagecreatefrompng( $filename ) ; —— 打开一个PNG图像文件
imagecreatefromstring( $filename ) ; —— 打开一个字符串图像文件(二进制图像)
imagecreatefromwbmp( $filename ) ; —— 打开一个WBMP图像文件
imagecreatefromwebp( $filename ) ; —— 打开一个WebP图像文件
imagecreatefromxbm( $filename ) ; —— 打开一个XBM文件
imagecreatefromxpm( $filename ) ; —— 打开一个XPM文件

$filename —— 图像的路径。

imagecreatefromgd2part ( $filename , $srcX ,  $srcY ,  $width , $height ) ; —— 从给定的 GD2 文件或 URL 中的部分新建一图像
$srcX —— 源点的x坐标。
$srcY —— 源点的y坐标。
$width —— 原图像的宽度
$height —— 原图像的高度

成功后返回图象资源,失败后返回 false 。

返回的图像资源需要赋予一个变量,以便后续操作

绘制图像

分配颜色:

imagecolorallocate (  $image ,  $red ,  $green ,  $blue ) : int
    $image —— 图像资源
    $red,$green,$blue —— 三原色,取值0~255

如果分配失败则返回 -1。
$color = imagecolorallocate($img,200,200,200);//创建颜色

填充背景:

imagefill ( $image ,  $x ,  $y ,  $color )  : bool

$color 表示 imagecolorallocate()分配颜色返回的变量

在 $image 图像的坐标 $x,$y(图像左上角为 0, 0)处用 $color 颜色执行区域填充
imagefill($img,0,0,$color);//填充颜色

画线:

imageline (  $image ,  $x1 ,  $y1 , $x2 , $y2 , $color ) : bool

用 $color 颜色在图像 $image 中从坐标 $x1,$y1 到 $x2,$y2(图像左上角为 0, 0)画一条线段。

画单一像素点:

imagesetpixel (  $image ,  $x , $y , $color ) : bool

在 $image 图像中用 $color 颜色在 $x,$y 坐标(图像左上角为 0,0)上画一个点。

画矩形:

imagefilledrectangle ( $image , $x1 , $y1 , $x2 , $y2 , $color ) : bool— 画一矩形并填充

在 image 图像中画一个用 color 颜色填充了的矩形,其左上角坐标为 x1,y1,右下角坐标为 x2,y2。0, 0 是图像的最左上角。

画多边形:

imagefilledpolygon ($image ,  $points ,  $num_points , $color ) : bool — 画一多边形并填充

$points  —— 参数是一个按顺序包含多边形各顶点的xy坐标的数组
$num_points —— 参数顶点的总数,也就是$points中点的个数,必须大于三
    $points = array(
        0,0,
        400,100,
        100,400
    );
    imagefilledpolygon ($img ,  $points ,  3 , $color );

画椭圆:

imageellipse (  $image , $cx , $cy , $width , $height , $color ) : bool — 画一个椭圆
        
在 $image图像资源 以宽$width ,高$height,($cx,$cy)为中心画一个椭圆
$color = imagecolorallocate($img,200,200,200);//画板背景
imageellipse (  $img , 250 , 250 , 400 , 300 , $color ) ;
    //宽度和高度的最大值为画板的宽高

画椭圆,并填充:

imagefilledellipse ( $image ,$cx ,  $cy , $width , $height , $color ) : bool
      
在 $image图像资源 以宽$width ,高$height,($cx,$cy)为中心画一个椭圆,并填充$color的颜色
$color = imagecolorallocate($img,200,200,200);//画板背景
$coloss = imagecolorallocate($img,200,0,0);//椭圆背景

imagefilledellipse (  $img , 250 , 250 , 400 , 300 ,$coloss) ;

画椭圆弧并填充:

imagefilledarc ($image , $cx , $cy , $width , $height , $start , $end , $color , $style ) : bool — 画一椭圆弧且填充
在 $image图像资源 以宽$width ,高$height,($cx,$cy)为中心,$start起点角度。$end终点角度
        
$style取值:
            IMG_ARC_CHORD 只是用直线连接了起始和结束点,
            IMG_ARC_PIE 则产生圆形边界
            IMG_ARC_NOFILL 指明弧或弦只有轮廓,不填充。
            IMG_ARC_EDGED 指明用直线将起始和结束点与中心点相连
    IMG_ARC_PIE 和 IMG_ARC_CHORD 是互斥的
<?php
    header('Content-Type: image/png');//文本格式
    $img = imagecreatetruecolor(500,500);//创建图片资源
    $col = imagecolorallocate($img,200,200,200);//创建颜色
    $color = imagecolorallocate($img,0,200,0);//创建颜色
    $colors = imagecolorallocate($img,0,0,200);//创建颜色
    $colo = imagecolorallocate($img,200,0,0);//创建颜色

    imagefilledarc ($img , 250 , 250 , 500 ,200 , 0 , 90 , $color , IMG_ARC_EDGED) ;
    imagefilledarc ($img , 250 , 250 , 500 ,200 , 90 , 240 , $colors , IMG_ARC_EDGED);
    imagefilledarc ($img , 250 , 250 , 500 ,200 , 240 , 360 , $colo , IMG_ARC_EDGED) ;
    imagefill($img,0,0,$col);//填充颜色
    imagepng($img);//以图片格式输出到浏览器
    imagedestroy($img);//释放文件
?>

水平画一行字体:

imagestring ( $image , $font , $x , $y , $str , $color ) : bool —— 水平地画一行字符串

 用 $color 颜色将字符串 $str 画到 $image 所代表的图像的 $x,$y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果 $font 是 1,2,3,4 或 5,则使用内置字体。

用到 TrueType 字体向图像写入文本:

imagettftext($image , $size ,$angle , $x ,$y , $color , $fontfile , $text ): array

$size —— 字体大小,像素
$angle —— 字体倾斜角度,
$x,$y —— 定义的第一个字体左上角的位置
$fontfile ——想要使用的 TrueType 字体的路径。 后缀为ttf,注意:字体的版权问题,不能随意使用他人字体
$text —— 字符串

返回一个含有 8 个单元的数组表示了文本外框的四个角,顺序为左下角,右下角,右上角,左上角。

计算TrueType文字所占区域:

imagettfbbox (  $size , $angle , $fontfile , $text ) : array

$size —— 字体大小,像素
$angle —— 字体倾斜角度,
$fontfile —— 字体文件。后缀为ttf,注意:字体的版权问题,不能随意使用他人字体
$text —— 字符串

imagettfbbox() array返回值:

--
0左下角 X 位置
1左下角 Y 位置
2右下角 X 位置
3右下角 Y 位置
4右上角 X 位置
5右上角 Y 位置
6左上角 X 位置
7左上角 Y 位置

拷贝图像的一部分:

imagecopy( $dst_im , $src_im , $dst_x ,$dst_y ,  $src_x , $src_y ,  $src_w ,$src_h ) : bool

将 $src_im 图像中坐标从 $src_x,$src_y 开始,宽度为 $src_w,高度为 $src_h 的一部分拷贝到 $dst_im 图像中坐标为 $dst_x 和 $dst_y 的位置上

拷贝并合并图像的一部分:

imagecopymerge (  $dst_im ,  $src_im , $dst_x , $dst_y , $src_x , $src_y , $src_w , $src_h ,  $pct ) : bool

将 $src_im 图像中坐标从 $src_x,$src_y 开始,宽度为 $src_w,高度为 $src_h 的一部分拷贝到 $dst_im 图像中坐标为 $dst_x 和 $dst_y 的位置上

$pct 表示 透明度,取值0~100,数值越大,越透明,

重采样拷贝部分图像并调整大小:

imagecopyresampled ( $dst_image, $src_image , $dst_x , $dst_y , $src_x , $src_y , $dst_w , $dst_h , $src_w , $src_h ) : bool

将在位置($src_x,$src_y)的宽度为src_w且高度为 $src_h的 $src_image中获取一个矩形区域,并将其放置在位置为($dst_x,$dst_y)且宽度为$dst_w且高度为$dst_h的dst_image矩形区域中。
输出图像

当前 PHP 版本所支持的图像类型:

<?php
        print_r(gd_info());
        
/*
Array ( [GD Version] => bundled (2.1.0 compatible) 
        [FreeType Support] => 1 
        [FreeType Linkage] => with freetype 
        [GIF Read Support] => 1 
        [GIF Create Support] => 1 
        [JPEG Support] => 1 
        [PNG Support] => 1 
        [WBMP Support] => 1 
        [XPM Support] => 1 
        [XBM Support] => 1 
        [WebP Support] => 1 
        [BMP Support] => 1 
        [JIS-mapped Japanese Font Support] => )
*/
?>

输出:

imagegif($image , [$filename] ) : bool — 输出图象到浏览器或文件。
imagejpeg($image , [$filename] ) : bool — 输出图象到浏览器或文件。
imagepng($image , [$filename] ) : bool — 以 PNG 格式将图像输出到浏览器或文件
imagewbmp($image , [$filename] ) : bool — 以 WBMP 格式将图像输出到浏览器或文件
imagewebp($image , [$filename] ) : bool — 将 WebP 格式的图像输出到浏览器或文件
imagexbm($image , [$filename] ) : bool — 将 XBM 图像输出到浏览器或文件

$filename —— 保存文件路径,可选

使用header(‘Content-Type: image/jpeg’); 告诉浏览器是这是图片,jpeg可以修改为自己图片的格式,如:png,gif

header()之前不能输出任何字符串,否则图片无法显示

当添加路径时,会在对应的文件夹内生成图片,这是使用header(‘Content-Type: text/html’);

释放图片
imagedestroy($image):bool

imagedestroy() 释放与 $image 关联的内存。

其他
imagesx($image) : int  —— 取得图像宽度
imagesy($image) : int  —— 取得图像高度

电脑自带字体位于

C:/Windows/Fonts

测试

注意字符编码格式,若出现乱码修改,可以在header()函数追加编码格式

header('Content-Type: text/html;charset=utf-8;');

显示图片文件:

<?php
    header('Content-Type: image/png');//文本格式
    $img = imagecreatetruecolor(500,500);//创建图片资源
    $color = imagecolorallocate($img,200,200,200);//创建颜色
    imagefill($img,0,0,$color);//填充颜色
    imagepng($img);//以图片格式输出到浏览器
    imagedestroy($img);//释放文件
?>

生成图片文件:

<?php
    header('Content-Type: text/html');
    $img = imagecreatetruecolor(500,500);
    $color = imagecolorallocate($img,200,200,200);
    imagefill($img,0,0,$color);
    if (imagepng($img,"../Img/1.png")) {
        echo "生成图片成功";
    }
    else{
        echo "生成图片失败";
    };//生成图片
    imagedestroy($img);
?>

案例:验证码

设置保存图片,引入网页,是当验证没法看的时候,点击刷新,删除之前的验证码然后生成新的验证码

<?php
    $arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
              "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    echo Captcha($arr,100,50,"C:/Windows/Fonts/Lobster-Regular.ttf",15,"../../Img/Captcha.png");
    
    function Captcha($arr=array(),$width=null,$height=null,$font_ttf="",$font_size=null,$save_file=""){
        /*
        设置默认值,防止带入变量为空没有显示
            $arr 验证码内容数组 —— array
            $width 图像宽度 —— int
            $height 图像高度 —— iint
            $font_ttf 字体路径 —— string
            $font_size 字体大小 —— int
            $save_file 保存地址 —— string
        */
        if($arr == null)
        {
            $arr = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
                    "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
        }
        if($width==null)
        {
            $width = 200;
        }   
        if($height==null)
        {
            $height = 100;
        }   
        if($font_ttf == "")
        {
            $font_ttf = "C:/Windows/Fonts/Lobster-Regular.ttf";
        } 
        if($font_size==null)
        {
            $font_size = 35;
        } 

        header("Content-type:text/html;charset=utf-8;");
        $img = imagecreatetruecolor($width,$height);
        $bg_color = imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));//背景颜色
        $pixel_color = imagecolorallocate($img,rand(100,150),rand(100,150),rand(100,150));//点的颜色
        $line_color = imagecolorallocate($img,rand(50,100),rand(50,100),rand(50,100));//线的颜色
        $font_color = imagecolorallocate($img,rand(0,50),rand(0,50),rand(0,50));//字体的颜色
        $string = "";//字符串
        imagefill($img,0,0,$bg_color);//背景填充
        for($i=0; $i<50 ; $i++)
        {
            imagesetpixel($img,rand(0,$width),rand(0,$height),$pixel_color);//画点
        }
        for($i=0; $i<4 ; $i++)
        {//画线
            imageline($img,rand(0,$width/5),rand($height/5,$height/5*4),rand($width/5*4,$width),rand($height/5,$height/5*4),$line_color);
        }
        for($i=0;$i<5;$i++)
        {//连接字符
            $string.= $arr[rand(0,count($arr)-1)];
        }
        //计算字符串的宽和高
        $font_arr = imagettfbbox($font_size,rand(-10,10),$font_ttf,$string);
        $font_width = abs($font_arr[2] - $font_arr[0]); 
        $font_height = abs($font_arr[5] - $font_arr[3]); 
        //设置字体的格式
        imagettftext($img,$font_size,rand(-10,10),($width-$font_width)/2,$height-($height-$font_height)/2,$font_color,$font_ttf,$string);
        imagepng($img,$save_file);//保存验证码
        imagedestroy($img);//释放图像资源
        return $string;
    }

?>

案例:水印

字体水印:

<?php
    $font_ttf = "C:/Windows/Fonts/Lobster-Regular.ttf";
    $img_url = "/PHPStudy/phpstudy_pro/WWW/PHP/Img/t.jpg";
    $color_array = [255,255,255];
    $x = 0; $y = 0;
    watermark($img_url,25,$font_ttf,$color_array,"YZ",$x,$y);
    function  watermark($src,$str_size,$font_ttf,$str_color,$str,$x,$y){
        /*
            $src —— 图片地址
            $str_size —— 字体大小
            $font_ttf —— 字体形式
            $str_color —— 字体颜色
            $str —— 字符串
            $x,$y —— 相对于图片的位置,左上角为(0,0)
        */
        header("Content-type:image/jpeg");
        $img = imagecreatefromjpeg($src);//图片资源
        $width = imagesx($img);//图片宽度
        $height = imagesy($img);//图片长度
        $font_color = imagecolorallocate($img,$str_color[0],$str_color[1],$str_color[2]);//字体的颜色
        //字体宽高
        $font_arr = imagettfbbox($str_size,0,$font_ttf,$str);
        $font_width = abs($font_arr[2] - $font_arr[0]); 
        $font_height = abs($font_arr[5] - $font_arr[3]); 
        //字体样式
        imagettftext($img,$str_size,0,$x,$y+$font_height,$font_color,$font_ttf,$str);
        imagejpeg($img);
        imagedestroy($img);
    }
?>

图片水印:

<?php
    $src_1 = "/PHPStudy/phpstudy_pro/WWW/PHP/Img/t.jpg";
    $src_2 = "/PHPStudy/phpstudy_pro/WWW/PHP/Img/Captcha.png";
    $x = 5;
    $y = 5;
    watermarkImg($src_1,$src_2,$x,$y);

    function  watermarkImg($src,$src_icon,$x,$y){
        /*
            $src —— 主图片
            $src_icon —— 图片水印
            $x 和 $y —— 水印的位置,按照$src_icon左上角(0,0)
        */
        header("Content-type:image/jpeg");
        $img = imagecreatefromjpeg($src);//图片资源
        $img_icon = imagecreatefrompng($src_icon);
        $width_icon = imagesx($img_icon);//图片宽度
        $height_icon = imagesy($img_icon);//图片长度
        imagecopymerge (  $img ,  $img_icon, $x , $y , 0 , 0 , $width_icon, $height_icon , 50 ) ;//将两张图片组合在一起
        imagejpeg($img);
        imagedestroy($img);//释放资源
        imagedestroy($img_icon);//释放资源
    }
?>
注意

路径问题:

获取图片资源和字体资源时,若使用相对路径,默认的地址为当前盘符的根目录,需要精确到当前目录

例如:

D:\PHPStudy\phpstudy_pro\WWW\PHP\demo1\7.php —— 这是代码的路径

则相对路径是相对于 D: 而言

因此找文件需要/PHPStudy/phpstudy_pro/WWW/PHP/Img/Lobster-Regular.ttf

绝对路径就任意了:
D:\PHPStudy\phpstudy_pro\WWW\PHP\Img/Lobster-Regular.ttf


案例:缩放与裁剪图片

剪切不能缩放:

<?php
        $src = "/PHPStudy/phpstudy_pro/WWW/PHP/Img/t.jpg";
        cutImg($src,300,300,500,400);

        function cutImg($src,$width,$height,$x,$y){
            /*
                $src  —— 要被剪切图片的地址
                $width —— 要切出来的图片的宽度
                $height—— 要切出来的图片的高度
                $x,$y —— 图片上剪切的位置
            */
            header("Content-type:image/jpeg");
            $img = imagecreatefromjpeg($src);//图片资源
            $width_img = imagesx($img);//图片宽度
            $height_img = imagesy($img);//图片长度

            //判断图片剪切是否超出$img,超出就修改宽高让其不会超出
            if(($x+$width)>$width_img)
            {
                $width = $width_img - $x;
            }
            if(($y+$height)>$height_img)
            {
                $height = $height_img - $y;
            }

            $imgs = imagecreatetruecolor($width,$height);//剪切图片存储位置

            imagecopy( $imgs , $img , 0 , 0 ,  $x , $y,  $width ,$height ) ;//将剪切的图片给画板
            imagejpeg($imgs);
            imagedestroy($img);//释放资源
            imagedestroy($imgs);//释放资源
        }
?>

剪切与缩放:

<?php
    $src = "/PHPStudy/phpstudy_pro/WWW/PHP/Img/t.jpg";
    $arr_color = array(200,200,200);
    cutImg($src,600,600,$arr_color,500,400,300,300,400,400,100,100);
    function cutImg($src, $width_local,$height_local,$color_local, $width_cute,$height_cute,$x_cute,$y_cute, $width_s,$height_s,$x_s,$y_s){
        /*
            $src  —— 要被剪切图片的地址
            $width_local,$height_local —— 存放剪切的画板宽度 ,高度
            $color_local —— 存放剪切的画板背景颜色
            
            $width_cute $height_cute —— 要切出来的图片的宽度 ,高度
            $x,$y —— 图片上剪切的位置,左上角坐标(0,0)
            $width_s,$height_s —— 切出来的图片放置到画板的宽度 ,高度
            $x_s,$y_s —— 图片放置到画板的位置,左上角坐标(0,0)
        */
        header("Content-type:image/jpeg");
        $img = imagecreatefromjpeg($src);//图片资源
        $width_img = imagesx($img);//图片宽度
        $height_img = imagesy($img);//图片长度
        $imgs = imagecreatetruecolor($width_local,$height_local);//剪切图片存储位置
        $imgs_color = imagecolorallocate($imgs,$color_local[0],$color_local[1],$color_local[2]);//设置背景画板颜色
        imagefill($imgs,0,0,$imgs_color);//填充画板颜色
        
        //判断图片剪切是否超出$img,超出就修改宽高让其不会超出
        if(($x_cute+$width_cute)>$width_img)
        {
            $width_cute = $width_img - $x_cute;
        }
        if(($y_cute+$height_cute)>$height_img)
        {
            $height_cute = $height_img - $y_cute;
        }

        //将图片剪切,并放置到新的画板,可以调整图像大小
        imagecopyresampled ( $imgs, $img , $x_s , $y_s , $x_cute , $y_cute , $width_s , $height_s , $width_cute , $height_cute );
        imagejpeg($imgs);
        imagedestroy($img);//释放资源
        imagedestroy($imgs);//释放资源
    }
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
建立一个博客系统需要以下步骤: 1. 确定需求,设计数据库表结构。 2. 搭建开发环境,安装 PHP 和 MySQL。 3. 编写代码,实现用户管理、博客管理、评论管理等功能。 4. 将代码部署到服务器上,配置好权限和安全设置。 以下是一个简单的博客系统的数据库表设计: 1. 用户表(users) |字段名|类型|说明| |----|----|----| |id|int|用户ID,自增主键| |username|varchar(50)|用户名| |password|varchar(50)|密码| |email|varchar(50)|邮箱| |avatar|varchar(100)|头像| 2. 博客表(blogs) |字段名|类型|说明| |----|----|----| |id|int|博客ID,自增主键| |title|varchar(100)|博客标题| |content|text|博客内容| |create_time|datetime|创建时间| |update_time|datetime|更新时间| |user_id|int|用户ID,外键| 3. 评论表(comments) |字段名|类型|说明| |----|----|----| |id|int|评论ID,自增主键| |content|text|评论内容| |create_time|datetime|创建时间| |user_id|int|用户ID,外键| |blog_id|int|博客ID,外键| 在 PHP 中,可以使用 mysqli 或 PDO 扩展来操作 MySQL 数据库。具体实现可以参考以下步骤: 1. 连接数据库: ```php $conn = new mysqli($servername, $username, $password, $dbname); ``` 2. 执行 SQL 语句,例如插入一条博客记录: ```php $title = "Hello World"; $content = "This is my first blog."; $user_id = 1; $sql = "INSERT INTO blogs (title, content, user_id) VALUES ('$title', '$content', $user_id)"; $conn->query($sql); ``` 3. 查询数据,例如查询所有博客: ```php $sql = "SELECT * FROM blogs"; $result = $conn->query($sql); while ($row = $result->fetch_assoc()) { echo $row["title"] . "<br>"; } ``` 4. 更新数据,例如更新一条博客记录: ```php $id = 1; $title = "Hello World 2"; $content = "This is my second blog."; $sql = "UPDATE blogs SET title='$title', content='$content' WHERE id=$id"; $conn->query($sql); ``` 5. 删除数据,例如删除一条博客记录: ```php $id = 1; $sql = "DELETE FROM blogs WHERE id=$id"; $conn->query($sql); ``` 以上是一个简单的博客系统的实现方法,但在实际开发中还需要考虑安全性、性能等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值