引言
GD库简介
安装GD库
1. 下载GD库
首先,从PHP官网下载GD库(
2. 配置PHP.ini
找到PHP的安装目录,打开php.ini文件。取消注释extension_dir和extension=php_gd2.dll这行代码。
extension_dir="C:/php/ext"
extension=php_gd2.dll
3. 重启Apache
重启Apache服务器,使配置生效。
图片处理基础
1. 打开图片
$image = imagecreatefromjpeg('path/to/image.jpg');
2. 获取图片尺寸
$width = imagesx($image);
$height = imagesy($image);
3. 设置图片格式
imagejpeg($image, 'path/to/output.jpg');
高级图片处理技巧
1. 缩放图片
$new_width = 200;
$new_height = 200;
$resize = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($resize, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($resize, 'path/to/output.jpg');
2. 裁剪图片
$cut_width = 100;
$cut_height = 100;
$cut_x = ($width - $cut_width) / 2;
$cut_y = ($height - $cut_height) / 2;
$cut = imagecreatetruecolor($cut_width, $cut_height);
imagecopy($cut, $image, 0, 0, $cut_x, $cut_y, $cut_width, $cut_height);
imagejpeg($cut, 'path/to/output.jpg');
3. 添加水印
$watermark = imagecreatefrompng('path/to/watermark.png');
imagecopy($image, $watermark, 0, 0, ($width - imagesx($watermark)) / 2, ($height - imagesy($watermark)) / 2, imagesx($watermark), imagesy($watermark));
imagejpeg($image, 'path/to/output.jpg');
4. 生成验证码
$captcha = imagecreatetruecolor(100, 30);
imagefilledrectangle($captcha, 0, 0, 100, 30, imagecolorallocate($captcha, 255, 255, 255));
$font_color = imagecolorallocate($captcha, 0, 0, 0);
$font_file = 'path/to/font.ttf';
imagettftext($captcha, 20, 0, 10, 25, $font_color, $font_file, '验证码');
imagejpeg($captcha, 'path/to/output.jpg');