一、PHP图片处理基础

1.1 图片处理函数库

PHP提供了多种图像处理函数库,其中最常用的是GD库。GD库支持多种图像格式,如GIF、JPEG、PNG等。

1.2 创建和操作图像

使用GD库,可以通过以下步骤创建和操作图像:

  • 使用imagecreate()imagecreatefromjpeg()等函数创建图像。
  • 使用imagecolorallocate()等函数设置图像颜色。
  • 使用imagestring()imagettftext()等函数在图像上添加文本。
  • 使用imagecopy()等函数在图像上进行复制、裁剪等操作。

1.3 输出图像

要将图像输出到浏览器,可以使用header()函数设置HTTP头信息,然后使用imagepng()imagejpeg()imagegif()等函数输出图像。

二、实战技巧

2.1 图片缩放

$source = imagecreatefromjpeg('source.jpg');
$width = 200;
$height = 150;
$destination = imagecreatetruecolor($width, $height);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));
imagepng($destination);

2.2 图片裁剪

$source = imagecreatefromjpeg('source.jpg');
$width = 200;
$height = 150;
$box = array('x' => 50, 'y' => 50, 'width' => $width, 'height' => $height);
$destination = imagecrop($source, $box);
imagepng($destination);

2.3 添加水印

使用imagestring()imagettftext()等函数可以在图像上添加水印。以下是一个示例代码:

$source = imagecreatefromjpeg('source.jpg');
$fontColor = imagecolorallocate($source, 255, 255, 255);
$fontFile = 'arial.ttf';
$text = 'Watermark';
imagettftext($source, 20, 0, 10, 30, $fontColor, $fontFile, $text);
imagepng($source);

2.4 图像格式转换

使用imagecreatetruecolor()imagepng()imagejpeg()等函数可以实现图像格式的转换。以下是一个示例代码:

$source = imagecreatefromjpeg('source.jpg');
$destination = imagecreatetruecolor(imagesx($source), imagesy($source));
imagecopy($destination, $source, 0, 0, 0, 0, imagesx($source), imagesy($source));
imagepng($destination, 'output.png');

三、总结