引言

接收图片

准备工作

首先,确保你的服务器上安装了PHP和GD库。GD库是PHP的一个扩展,用于处理图像。

创建表单

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

PHP接收图片

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
    $file = $_FILES['image'];
    $tmp_name = $file['tmp_name'];
    $name = $file['name'];
    $size = $file['size'];
    $error = $file['error'];

    // 检查上传错误
    if ($error !== UPLOAD_ERR_OK) {
        die("上传错误:{$error}");
    }

    // 保存图片
    move_uploaded_file($tmp_name, "uploads/{$name}");
    echo "图片上传成功!";
} else {
    echo "请选择一个文件上传。";
}
?>

保存图片

图片处理

<?php
// 裁剪图片
function cropImage($imagePath, $newWidth, $newHeight) {
    $image = imagecreatefromjpeg($imagePath);
    $width = imagesx($image);
    $height = imagesy($image);

    // 计算裁剪位置
    $x = ($width - $newWidth) / 2;
    $y = ($height - $newHeight) / 2;

    // 创建新图像
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, $x, $y, $newWidth, $newHeight, $width, $height);

    // 保存新图像
    imagejpeg($newImage, "uploads/cropped_{$name}");
    imagedestroy($image);
    imagedestroy($newImage);
}

// 使用函数裁剪图片
cropImage("uploads/{$name}", 200, 200);
?>

错误处理

总结