引言

图片上传

1. 准备工作

首先,确保您的服务器已安装PHP和GD库,GD库是PHP处理图像的扩展库。

2. HTML表单

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" value="上传">
</form>

3. PHP处理

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $image = $_FILES['image']['tmp_name'];
    $upload_dir = 'uploads/';
    $filename = basename($_FILES['image']['name']);
    $destination = $upload_dir . $filename;

    if (move_uploaded_file($image, $destination)) {
        echo "图片上传成功!";
    } else {
        echo "图片上传失败!";
    }
}
?>

图片展示

1. 创建图片列表

$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');

2. 遍历数组并展示图片

foreach ($images as $image) {
    echo '<img src="' . $upload_dir . $image . '" alt="' . $image . '">';
}

图片浏览技巧

1. 分页展示

// 假设每页展示5张图片
$per_page = 5;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $per_page;

// 获取当前页的图片
$images = array_slice($images, $offset, $per_page);

2. 缩略图

function create_thumbnail($source, $destination, $width, $height) {
    list($original_width, $original_height) = getimagesize($source);
    $ratio = min($width / $original_width, $height / $original_height);
    $new_width = $original_width * $ratio;
    $new_height = $original_height * $ratio;

    $thumbnail = imagecreatetruecolor($width, $height);
    $source_image = imagecreatefromjpeg($source);

    imagecopyresampled($thumbnail, $source_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

    imagejpeg($thumbnail, $destination);
}

create_thumbnail($upload_dir . $image, $upload_dir . 'thumbnail_' . $image, 100, 100);

3. 图片预览

echo '<img src="' . $destination . '" alt="' . $filename . '" style="max-width: 200px; max-height: 200px;">';

总结