安装GD扩展
在开始使用GD扩展之前,你需要确保PHP环境中已经安装并启用了GD模块。大多数PHP安装都默认包含了GD库,但你可以使用以下命令来检查:
<?php
phpinfo();
?>
在phpinfo()输出的页面中查找“GD”部分,确认它是否被启用。
基本操作
1. 加载图片
<?php
$image = imagecreatefromjpeg('example.jpg');
?>
2. 创建图片
<?php
$width = 400;
$height = 300;
$image = imagecreatetruecolor($width, $height);
?>
3. 绘制图形
GD库提供了多种函数来绘制线条、矩形、椭圆等图形。以下是一个绘制矩形的示例:
<?php
$color = imagecolorallocate($image, 255, 0, 0); // 红色
imagefilledrectangle($image, 50, 50, 350, 250, $color);
?>
4. 输出图片
<?php
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
?>
高级技巧
1. 图片切割
<?php
$sourceImage = imagecreatefromjpeg('example.jpg');
$width = 200;
$height = 150;
for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
$targetImage = imagecreatetruecolor($width, $height);
imagecopy($targetImage, $sourceImage, 0, 0, $i * $width, $j * $height, $width, $height);
imagejpeg($targetImage, "part_{$i}_{$j}.jpg");
imagedestroy($targetImage);
}
}
imagedestroy($sourceImage);
?>
2. 图片转换为黑白
<?php
$sourceImage = imagecreatefromjpeg('example.jpg');
$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
$black = imagecolorallocate($sourceImage, 0, 0, 0);
$white = imagecolorallocate($sourceImage, 255, 255, 255);
for ($y = 0; $y < $height; $y++) {
for ($x = 0; $x < $width; $x++) {
$color = imagecolorat($sourceImage, $x, $y);
$gray = (int) (imagecolorsforindex($sourceImage, $color)['red'] * 0.3 + imagecolorsforindex($sourceImage, $color)['green'] * 0.59 + imagecolorsforindex($sourceImage, $color)['blue'] * 0.11);
if ($gray < 128) {
imagesetpixel($sourceImage, $x, $y, $black);
} else {
imagesetpixel($sourceImage, $x, $y, $white);
}
}
}
imagejpeg($sourceImage, 'black_and_white.jpg');
imagedestroy($sourceImage);
?>
常见问题
1. 图片加载失败
2. 图像处理速度慢
尝试减少图像尺寸或降低图像质量,这可以加快处理速度。