引言
PHP图片上传基础
1. HTML表单设计
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*">
<input type="submit" value="Upload Image">
</form>
这里,enctype="multipart/form-data" 是关键,它允许表单数据包含文件。
2. PHP脚本处理
在服务器端,我们使用PHP脚本来处理上传的文件。以下是一个基本的上传脚本:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
$image = $_FILES['image'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($image['name']);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 检查文件类型
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
exit;
}
// 检查文件是否已上传
if (move_uploaded_file($image["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( $image["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
这段代码检查了上传的文件类型,并确保文件已成功上传到服务器。
图片压缩技巧
1. 使用PHP内置函数
<?php
$image = imagecreatefromjpeg("path/to/image.jpg");
imagejpeg($image, "path/to/compressed.jpg", 75); // 75 是压缩质量(0-100)
imagedestroy($image);
?>
2. 使用第三方库
<?php
// 使用GD库
$image = imagecreatefromjpeg("path/to/image.jpg");
imagejpeg($image, "path/to/compressed.jpg", 75);
imagedestroy($image);
// 使用Imagick库
$image = new Imagick("path/to/image.jpg");
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(75);
$image->writeImage("path/to/compressed.jpg");
?>
3. 调整图片尺寸
<?php
$image = imagecreatefromjpeg("path/to/image.jpg");
$width = 800;
$height = 600;
$dst_image = imagecreatetruecolor($width, $height);
imagecopyresampled($dst_image, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));
imagejpeg($dst_image, "path/to/compressed.jpg");
imagedestroy($image);
imagedestroy($dst_image);
?>