引言
准备工作
- 创建一个表单用于上传图片。
- 使用PHP处理上传的图片。
- 使用GD库生成缩略图。
创建上传表单
<form action="upload.php" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="image" />
<input type="submit" value="上传" />
</form>
这里,action 属性指定了处理上传的PHP脚本(upload.php),method 属性指定了使用POST方法发送数据,enctype 属性确保文件数据被正确地发送。
处理上传的图片
- 检查是否有文件被上传。
- 验证文件类型和大小。
- 保存上传的文件到服务器。
以下是upload.php的示例代码:
<?php
// 设置允许的图片类型和最大文件大小
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
$max_size = 5000000; // 5MB
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
$file = $_FILES['image'];
$file_name = $file['name'];
$file_type = $file['type'];
$file_size = $file['size'];
$temp_name = $file['tmp_name'];
// 验证文件类型
if (!in_array($file_type, $allowed_types)) {
die('不支持的图片类型。');
}
// 验证文件大小
if ($file_size > $max_size) {
die('文件大小超过。');
}
// 保存文件
$destination = "uploads/" . $file_name;
move_uploaded_file($temp_name, $destination);
echo "图片上传成功!";
} else {
echo "请选择一个图片文件上传。";
}
?>
生成缩略图
- 打开上传的图片。
- 设置缩略图的大小。
- 创建一个新的图像资源。
- 将上传的图片复制到新的图像资源中。
- 保存新的图像资源。
以下是生成缩略图的示例代码:
<?php
// 获取图片路径和缩略图大小
$image_path = "uploads/image.jpg";
$thumbnail_size = array(100, 100); // 宽度和高度
// 打开图片
$image = imagecreatefromjpeg($image_path);
// 获取图片宽度和高度
$width = imagesx($image);
$height = imagesy($image);
// 计算缩略图比例
$ratio = min($thumbnail_size[0] / $width, $thumbnail_size[1] / $height);
// 计算新的宽度和高度
$new_width = $width * $ratio;
$new_height = $height * $ratio;
// 创建新的图像资源
$thumbnail = imagecreatetruecolor($thumbnail_size[0], $thumbnail_size[1]);
// 调整颜色以保持透明度
imagealphablending($thumbnail, false);
imagesavealpha($thumbnail, true);
// 复制图片到新的图像资源
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// 保存缩略图
$thumbnail_path = "uploads/thumbnail.jpg";
imagejpeg($thumbnail, $thumbnail_path);
// 释放资源
imagedestroy($image);
imagedestroy($thumbnail);
echo "缩略图生成成功!";
?>