PHP图像处理

1 图像处理应用场景

1.缩略图

2.验证码

3.水印

4.图片裁剪

2 PHP绘图的基本步骤

(1)开启GD扩展库

(2)将图像加载到内存中进行处理

  • 创建画布资源
  • 准备颜色
  • 在画布上画图像或文字
  • 输出最终图像或保存图像
  • 释放画布资源

3 绘制各种线条

3.1 绘制线条

<?php
// 1.新建一个真彩色图像,成功后返回图象资源,失败后返回 FALSE 。
$img = imagecreatetruecolor(300, 300);
// 2.为一幅图像分配颜色,返回一个标识符,代表了RGB组成的颜色
$green = imagecolorallocate($img, 0, 148, 85);
$red = imagecolorallocate($img, 255, 0, 0);
// 3.区域填充
imagefill($img, 0, 0, $green);
// 4.绘制一个线条
$line = imageline($img, 0, 0, 300, 300, $red);

header('Content-Type:image/png');
imagepng($img);
imagedestroy($img);

3.2 绘制矩形

<?php
// 1.新建一个真彩色图像,成功后返回图象资源,失败后返回 FALSE 。
$img = imagecreatetruecolor(300, 300);
// 2.为一幅图像分配颜色,返回一个标识符,代表了RGB组成的颜色
$green = imagecolorallocate($img, 0, 148, 85);
$red = imagecolorallocate($img, 255, 0, 0);
// 3.区域填充
imagefill($img, 0, 0, $green);
// 4.绘制矩形
imagerectangle($img, 25, 25, 100, 100, $red);		// 线条矩形
imagefilledrectangle($img, 100, 100, 200, 200, $red);// 实心矩形

3.3 绘制圆形、椭圆

<?php
// 1.新建一个真彩色图像,成功后返回图象资源,失败后返回 FALSE 。
$img = imagecreatetruecolor(300, 300);
// 2.为一幅图像分配颜色,返回一个标识符,代表了RGB组成的颜色
$green = imagecolorallocate($img, 0, 148, 85);
$red = imagecolorallocate($img, 255, 0, 0);
// 3.区域填充
imagefill($img, 0, 0, $green);
// 4.绘制圆形、椭圆
imageellipse($img, 150, 150, 50, 50, $red);			// 绘制空心圆形
imageellipse($img, 150, 150, 50, 100, $red);		// 绘制空心椭圆
imagefilledellipse($img, 100, 100, 50, 50, $red);	// 绘制实心圆形
imagefilledellipse($img, 200, 200, 20, 30, $red);	// 绘制实心椭圆

header('Content-Type:image/png');
imagepng($img);
imagedestroy($img);

3.4 绘制文字

<?php
$img = imagecreatetruecolor(500, 300);
$red = imagecolorallocate($img, 255, 0, 0);
$white = imagecolorallocate($img, 255,255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
imagefill($img, 0, 0, $red);
$font_path = getcwd().'/simkai.ttf';
$text = '我爱你中国';
imagettftext($img, 19, 0, 65, 65, $white, $font_path, $text);
header('Content-Type:image/png');
imagepng($img);
imagedestroy($img);
原文地址:https://www.cnblogs.com/falling-maple/p/9304079.html