图片上传
表单设置:确保表单的enctype
属性设置为multipart/form-data
,以便可以上传文件。
接收文件:使用$_FILES
全局数组接收上传的文件信息。
验证文件:检查文件类型、大小等,确保其符合预期。
保存文件:将文件保存到服务器上的指定位置。
<?php
if (isset($_FILES['img'])) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['img']['name']);
if (move_uploaded_file($_FILES['img']['tmp_name'], $uploadFile)) {
echo "文件上传成功。";
} else {
echo "文件上传失败。";
}
}
?>
图片删除
使用unlink()
函数:调用unlink()
函数删除文件。
<?php
$imagePath = 'uploads/image.jpg';
if (file_exists($imagePath)) {
if (unlink($imagePath)) {
echo "图片删除成功。";
} else {
echo "图片删除失败。";
}
} else {
echo "文件不存在。";
}
?>
图片缩放
<?php
$imagePath = 'uploads/image.jpg';
$targetPath = 'uploads/thumbnail_image.jpg';
$targetWidth = 100;
list($width, $height) = getimagesize($imagePath);
$ratio = $width / $height;
$newHeight = $targetWidth / $ratio;
$image = imagecreatetruecolor($targetWidth, $newHeight);
$imageContent = imagecreatefromjpeg($imagePath);
imagecopyresampled($image, $imageContent, 0, 0, 0, 0, $targetWidth, $newHeight, $width, $height);
imagejpeg($image, $targetPath);
imagedestroy($image);
imagedestroy($imageContent);
?>
图片裁剪
<?php
$imagePath = 'uploads/image.jpg';
$targetPath = 'uploads/cropped_image.jpg';
$targetWidth = 100;
$targetHeight = 100;
$x = 50;
$y = 50;
$image = imagecreatetruecolor($targetWidth, $targetHeight);
$imageContent = imagecreatefromjpeg($imagePath);
imagecopyresampled($image, $imageContent, 0, 0, $x, $y, $targetWidth, $targetHeight, $width - $x * 2, $height - $y * 2);
imagejpeg($image, $targetPath);
imagedestroy($image);
imagedestroy($imageContent);
?>