引言
准备工作
在开始之前,请确保您的服务器已安装并配置了PHP环境,并且安装了GD库(PHP的图像处理库)。
图片处理函数介绍
imagecreatetruecolor($width, $height):创建一个空白图像,颜色深度为24位。imagecopyresampled():将一幅图像内容复制并调整大小到另一个图像上。imagejpeg()、imagepng()、imagegif():将图像输出到浏览器或文件。
多比例图片处理技巧
1. 图片缩放
<?php
// 创建图像资源
$src_img = imagecreatefromjpeg('path/to/your/image.jpg');
$width = 300;
$height = 200;
// 创建新图像
$dst_img = imagecreatetruecolor($width, $height);
// 缩放图像
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, imagesx($src_img), imagesy($src_img));
// 输出图像
imagejpeg($dst_img, 'path/to/save/resized/image.jpg');
?>
2. 图片裁剪
<?php
// 创建图像资源
$src_img = imagecreatefromjpeg('path/to/your/image.jpg');
$x = 100;
$y = 100;
$width = 200;
$height = 150;
// 创建新图像
$dst_img = imagecreatetruecolor($width, $height);
// 裁剪图像
imagecopy($dst_img, $src_img, 0, 0, $x, $y, $width, $height);
// 输出图像
imagejpeg($dst_img, 'path/to/save/cropped/image.jpg');
?>
3. 水平/垂直翻转
以下是一个图像水平/垂直翻转的示例代码:
<?php
// 创建图像资源
$src_img = imagecreatefromjpeg('path/to/your/image.jpg');
$width = imagesx($src_img);
$height = imagesy($src_img);
// 创建新图像
$dst_img = imagecreatetruecolor($width, $height);
// 水平翻转
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$color = imagecolorat($src_img, $x, $y);
imagesetpixel($dst_img, $width - $x - 1, $y, $color);
}
}
// 输出图像
imagejpeg($dst_img, 'path/to/save/flip/image.jpg');
// 重置图像资源
imagedestroy($src_img);
imagedestroy($dst_img);
?>