引言
图片上传
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
$image = $_FILES['image'];
$uploadPath = 'uploads/' . $image['name'];
if (move_uploaded_file($image['tmp_name'], $uploadPath)) {
echo "文件上传成功!";
} else {
echo "文件上传失败!";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" value="上传" />
</form>
在上面的代码中,我们首先检查是否有文件上传请求。如果有,我们获取上传的文件并尝试将其移动到服务器上的指定目录。
图片尺寸调整
<?php
$imagePath = 'uploads/image.jpg';
list($width, $height) = getimagesize($imagePath);
$desiredWidth = 100;
$desiredHeight = ($height * $desiredWidth) / $width;
$image = imagecreatetruecolor($desiredWidth, $desiredHeight);
$imageContent = imagecreatefromjpeg($imagePath);
imagecopyresampled($image, $imageContent, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $width, $height);
imagejpeg($image, 'uploads/resized_image.jpg');
图片格式转换
<?php
$imagePath = 'uploads/image.jpg';
$imageContent = imagecreatefromjpeg($imagePath);
imagepng($imageContent, 'uploads/image.png');
图片裁剪
<?php
$imagePath = 'uploads/image.jpg';
$sourceImage = imagecreatefromjpeg($imagePath);
$desiredWidth = 100;
$desiredHeight = 100;
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);
$sourceX = ($sourceWidth - $desiredWidth) / 2;
$sourceY = ($sourceHeight - $desiredHeight) / 2;
$destinationImage = imagecreatetruecolor($desiredWidth, $desiredHeight);
imagecopy($destinationImage, $sourceImage, 0, 0, $sourceX, $sourceY, $desiredWidth, $desiredHeight);
imagejpeg($destinationImage, 'uploads/cropped_image.jpg');
添加水印
<?php
$imagePath = 'uploads/image.jpg';
$watermarkText = 'Watermark';
$fontSize = 20;
$fontColor = imagecolorallocate($image, 255, 255, 255);
$fontFile = 'arial.ttf';
$sourceImage = imagecreatefromjpeg($imagePath);
$watermarkImage = imagettftext($sourceImage, $fontSize, 0, 10, 10, $fontColor, $fontFile, $watermarkText);
imagejpeg($sourceImage, 'uploads/watermarked_image.jpg');