PHP图片处理与验证码生成
PHP的GD库可以处理图片和生成验证码。今天说说图片处理和验证码的实现。
生成验证码图片。
```php
function generateCaptcha(int $width = 150, int $height = 50, int $length = 4): string
{
$image = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgColor);
// 干扰线
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(150, 200), rand(150, 200), rand(150, 200));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
// 干扰点
for ($i = 0; $i < 100; $i++) {
$color = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
}
// 验证码文字
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < $length; $i++) {
$char = $chars[rand(0, strlen($chars) - 1)];
$code .= $char;
$textColor = imagecolorallocate($image, rand(0, 80), rand(0, 80), rand(0, 80));
$x = 20 + $i * 30 + rand(-3, 3);
$y = rand(15, 35);
imagestring($image, 5, $x, $y, $char, $textColor);
}
ob_start();
imagepng($image);
$imageData = ob_get_clean();
imagedestroy($image);
return base64_encode($imageData);
}
echo "
\n";
?>
图片缩放。
```php
function resizeImage(string $sourcePath, string $destPath, int $maxWidth, int $maxHeight): void
{
$info = getimagesize($sourcePath);
[$width, $height, $type] = $info;
$ratio = min($maxWidth / $width, $maxHeight / $height);
$newWidth = (int)($width * $ratio);
$newHeight = (int)($height * $ratio);
$sourceImage = match ($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($sourcePath),
IMAGETYPE_PNG => imagecreatefrompng($sourcePath),
IMAGETYPE_GIF => imagecreatefromgif($sourcePath),
default => throw new RuntimeException("不支持的图片类型"),
};
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($thumb, $destPath, 85);
imagedestroy($sourceImage);
imagedestroy($thumb);
}
?>
图片水印。
```php
function addWatermark(string $sourcePath, string $destPath, string $text): void
{
$image = imagecreatefromjpeg($sourcePath);
$width = imagesx($image);
$height = imagesy($image);
$textColor = imagecolorallocatealpha($image, 255, 255, 255, 60);
$fontFile = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';
if (file_exists($fontFile)) {
$box = imagettfbbox(20, 0, $fontFile, $text);
$textWidth = $box[2] - $box[0];
$x = $width - $textWidth - 10;
$y = $height - 10;
imagettftext($image, 20, 0, $x, $y, $textColor, $fontFile, $text);
} else {
$x = $width - strlen($text) * imagefontwidth(5) - 10;
$y = $height - 30;
imagestring($image, 5, $x, $y, $text, $textColor);
}
imagejpeg($image, $destPath, 90);
imagedestroy($image);
}
?>
GD库的功能很丰富,图片缩放、裁剪、水印、验证码生成都能做。处理大图片时注意内存占用,建议先检查可用内存再操作。