1. 图片上传基础
1.1 配置上传目录
首先,需要确保服务器上的一个目录允许文件写入,并设置正确的权限。
$uploadDir = 'uploads/';
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
1.2 检查文件上传
在处理文件上传时,PHP提供了一个非常方便的函数$_FILES,可以用来检查上传的文件。
if ($_FILES['file']['error'] == 0) {
// 文件上传成功
} else {
// 文件上传失败,错误代码见:http://www.php.net/manual/en/features.file-upload.errors.php
}
1.3 文件类型验证
$validTypes = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
if (!in_array(getimagesize($_FILES['file']['tmp_name'])[2], $validTypes)) {
// 不是有效的图片类型
}
1.4 保存文件
将上传的文件移动到服务器上的指定目录。
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . basename($_FILES['file']['name']));
2. 图片裁切与缩放
2.1 使用GD库裁切图片
function cropImage($sourcePath, $destinationPath, $x, $y, $width, $height) {
list($sourceWidth, $sourceHeight, $type) = getimagesize($sourcePath);
switch ($type) {
case IMAGETYPE_JPEG:
$sourceImage = imagecreatefromjpeg($sourcePath);
break;
case IMAGETYPE_PNG:
$sourceImage = imagecreatefrompng($sourcePath);
break;
case IMAGETYPE_GIF:
$sourceImage = imagecreatefromgif($sourcePath);
break;
}
$croppedImage = imagecrop($sourceImage, ['x' => $x, 'y' => $y, 'width' => $width, 'height' => $height]);
imagejpeg($croppedImage, $destinationPath);
imagedestroy($sourceImage);
imagedestroy($croppedImage);
}
2.2 图片缩放
function resizeImage($sourcePath, $destinationPath, $width, $height) {
list($sourceWidth, $sourceHeight, $type) = getimagesize($sourcePath);
switch ($type) {
case IMAGETYPE_JPEG:
$sourceImage = imagecreatefromjpeg($sourcePath);
break;
case IMAGETYPE_PNG:
$sourceImage = imagecreatefrompng($sourcePath);
break;
case IMAGETYPE_GIF:
$sourceImage = imagecreatefromgif($sourcePath);
break;
}
$targetImage = imagecreatetruecolor($width, $height);
imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $width, $height, $sourceWidth, $sourceHeight);
imagejpeg($targetImage, $destinationPath);
imagedestroy($sourceImage);
imagedestroy($targetImage);
}